0

Following code

#include <stdio.h> int main( int argc, char** argv ) { const char *s = ""; if (s == '\0') { int x = 0; } return 0; } 

It does not go in the loop. Why ? ,

3
  • 1
    You're comparing the address of a string with a character (promoted to an integer), but yes, "" is just one null character. Commented Jan 28, 2013 at 5:30
  • 6
    I don't see any loop in your code. Commented Jan 28, 2013 at 5:31
  • 3
    It does not go in the loop. Why ? There is no loop. That's like asking a homeless man why he doesn't go home. Commented Jan 28, 2013 at 5:33

3 Answers 3

4

You've defined s as a pointer to char. As it happens, '\0' is an integer constant expression with the value 0 -- the definition of a null pointer constant.

IOW, you're doing the equivalent of if (s == NULL). Since s actually points at a string literal, it's not a null pointer, so the comparison is false.

I'd guess what you intended is if (*s == '\0') ..., which should compare as true.

Sign up to request clarification or add additional context in comments.

Comments

2

Try

 if (*s == '\0') { int x = 0; } 

You want to compare the value of s, not it's memory address.

Comments

1

s is a pointer, this version compares pointer

const char *s = null; if (s == '\0') { int x = 0; } return 0; 

and this version compares first element of string to detect a null string:

if (s[0] == '\0') { int x = 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.