I am trying to modify a code to adjust it to my liking. In order to do so I needed to understand what do we mean by if (!String) in C language if someone has any ideas ?
Example :
const char *String;
if (!String) {
   //do something
}
I am trying to modify a code to adjust it to my liking. In order to do so I needed to understand what do we mean by if (!String) in C language if someone has any ideas ?
Example :
const char *String;
if (!String) {
   //do something
}
 
    
     
    
    From the C Standard (6.5.3.3 Unary arithmetic operators)
5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).
And (6.3.2.3 Pointers)
3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. 66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
So this if statement
if (!String) {
   //do something
}
checks whether the pointer String is equal to null-pointer provided that the pointer String was initialized.
While for example this statement
if (!*String) {
   //do something
}
checks whether the character pointed to by the pointer is equal to the null-terminating character '\0'.
If you'll include standard header <iso646.h> in your C-program then you can substitute the operator ! for the word not.
For example
#include <iso646.h>
//...
if ( not String ) {
   //do something
}
 
    
    It is a short way of writing if(String == NULL).
Often we instead write if(String) which is short for if(String != NULL). Note that this does NOT check if it points at a valid location. This code compiles but will (or may) fail:
char * str = strdup("Hello World!");
free(str);
if(str) { // If str is not a null pointer'
    puts(str); // str is pointing to memory that we have freed.
}              
Trying to print str when it's no longer pointing at a valid location is undefined behavior. The program may print "Hello World!", crash or something else.
