Isn't '\0' != 0 true?

274 views Asked by At

I am having some difficulties in understanding the condition of the while loop given below:

int main()
{
    char s[]="Let's Get it Started";
    int i=0;
    while(s[i]!=0)
    { 
       //do something
       ++i

    }
}

I know that string is stored with the last character as \0 which has the ASCII value as 0. In the while loop, it is comparing the value of the particular characters of the array. So when it reaches \0 condition would be like

'\0' != 0 // I guess this is also true

So isn't this an infinite loop?

3

There are 3 answers

3
Mohit Jain On BEST ANSWER

In C, '\0' has same value (and even type) as 0. Both are ints with 0 value.

So isn't this an infinite loop ?

So, no it is not an infinite loop because of assumption that \0 and 0 are different. But the loops may be infinited for other factors not in the scope of this question.

From C11 specs section 5.2.1/2 Character sets

A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string.

0
cwfighter On

Maybe you have gone into errors. you can seek ASCII table, '\0'-->0, '0'-->48.

In your codes, while(s[i] != 0), the 0 is int, not a char, so '\0' == 0 is true.

By the way, you can write codes below:

int a = '\0';
int b = '0';
printf("%d  %d\n", a, b);

I believe you can know the problems clearly. So It is not a infinite loop.

0
FELIPE_RIBAS On

You seem to be making a little confusion between ascii letters '0' and '\0'. The first one is the ascii character '0' which has an equivalent number (48) according to ascii table. But when using the escape bar before the zero '\0' you are using the null character (which is different from the null number) which, by the way, has all its bits zeroed. Therefore, an ascii character with all its bits set to zero is the same as the number 0.

Thus, this is not an infinite loop because when comparing the null character at the end, it is equal to number 0.