开发者

How do I check if a const char*'s value is defined?

My application reads settings from a conf file first, and then those options can be overwritten from the cli arguments. After it loads the settings from the conf, I need to check if the require values are set but I'm stuck at making it check the variables.

Sample code:

#include <stdio.h>

int main() {

const char* test;

if (test != NULL)
   std::cout << test << "\n";
else
   std::cout <开发者_如何学JAVA< "no value set\n";

return 0;
}

What did I do wrong?


You didn't initialize test. If you want it to be NULL initially, you have to set it:

const char* test = NULL;


C and C++ do not initialize pointers to NULL automatically. If you do not assign it a value, it still has a value, it is just an unknown, indeterminate value. It could be NULL, it could be something else.

In your sample code, test has a value, but it is unknown. So your if-statement might or might not be true.


As an alternative that is more idiomatic for C++, you could use a string and check whether it's empty after your init completes:

#include <string>

std::string test;   // default constructor produces an empty string

// do the config load

if (test.empty())
{
  // config error
}

Note that if the data semantics here include an empty value being legitimate, this alternative is not viable.


You don't.

You cannot check a "defined" state in C/C++ if you haven't "defined" that state yourself. Don't leave initialization up to your compiler implementation if you are doing something like this.

Initialize your pointer to NULL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜