0

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
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 5
    It's the same thing as `if (String == NULL)` – Jabberwocky Jun 13 '19 at 12:43
  • 1
    `const char*` can be interpreted as a boolean when the value of the pointer > 0. The `!` operator inverses that result. So that check returns true when `String == 0` – Neijwiert Jun 13 '19 at 12:43
  • If the value of the pointer is zero: i.e., it's null. – Mad Physicist Jun 13 '19 at 12:44
  • 3
    Note that in your snippet (taken as a whole program) `String` is not initialized or otherwise assigned a value. Testing with `if (!String)` (or otherwise inspecting its value) invokes UB. – pmg Jun 13 '19 at 12:44

2 Answers2

0

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
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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.

klutt
  • 30,332
  • 17
  • 55
  • 95