How to check if const char * is defined?

My application first reads the parameters from the conf file, and then these parameters can be overwritten from the cli arguments. After it loads the settings from conf, I need to check if the required values ​​are set, but I'm stuck in checking variables.

Code example:

#include <stdio.h>

int main() {

const char* test;

if (test != NULL)
   std::cout << test << "\n";
else
   std::cout << "no value set\n";

return 0;
}

What have I done wrong?

+3
source share
4 answers

You did not initialize test. If you want it to be NULLinitially, you must install it:

const char* test = NULL;
+7
source

C ++ NULL . , , . NULL, - .

test , . , if-statement .

0

, ++, , init:

#include <string>

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

// do the config load

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

, , .

0

.

You cannot check for a “specific” state in C / C ++ unless you have “determined” what to state yourself. Do not leave initialization until your compiler is implemented if you are doing something like this.

Initialize a pointer to NULL.

0
source

Source: https://habr.com/ru/post/1778156/


All Articles