Home > Software engineering >  C Programming Negation: What is the difference between !string and !*string
C Programming Negation: What is the difference between !string and !*string

Time:10-15

A question regarding programming negation.

Please correct me if my understanding is wrong:

  • !string - checks if the char string is not NULL;
  • !*string - checks if the char string is pointing to something

Your explanations are appreciated and thank you in advance.

CodePudding user response:

  • !string: returns true if the string is pointing to NULL
  • !*string: returns true if the first char in the string, that the string is pointing to is == 0

CodePudding user response:

In C, a string is a 0-terminated array of characters.

If string is an array, it makes no sense to check !string, since it would always be false.

char string[100];
...
if (!string) // makes no sense

I assume string is a pointer that points to a string (to the first character thereof).

char* string;
...
if (!string) // makes perfect sense

!string means "string is a NULL pointer" (i.e. there is no character it points to; no string to work on).

!*string means "string points to a \0 character" (i.e. to the string terminator; the length of the pointed-to string is zero).

CodePudding user response:

If string is NULL, it does not point anywhere.

If string does point somewhere, hopefully it points to an array of characters, terminated by a null byte. It might point to a long string, like "supercalafragalisticespialadocious", or it might point to a short string like "hello", or it might point to a very short string like "x", or it might point to the empty string, "".

When you're working with pointers, you have to be careful to distinguish between the pointer and what it points to.

Your variable string is a pointer. And the expression *string refers to the first character pointed to by string. If string points to "supercalafragalisticespialadocious", then *string is the character 's'. If string points to "hello", then *string is the character 'h'. And if string points to the empty string "", then *string is the null character '\0'.

So we have:

  • the condition if(string) succeeds if string is nonzero, that is, if string is not the NULL pointer, that is, if string points somewhere
  • the condition if(!string) succeeds if string is zero, that is, if string is the NULL pointer, that is, if string points nowhere
  • the condition if(*string) succeeds if the character pointed to by string is nonzero, that is, if string is not an empty string
  • the condition if(!*string) succeeds if the character pointed to by string is zero, that is, if string is an empty string

Finally, if string is a NULL pointer, then both if(*string) and if(!*string) are likely to crash, since they try to access the character pointed to by string, but a null pointer by definition points nowhere, so you can't fetch the pointed-to character to see if it's 0 or not.

  •  Tags:  
  • c
  • Related