Search code examples
cwhile-loopcharprintfc-strings

using 0 instead of '\0' in C program


why my program did not go in infinite loop. I have not used '\0' for testing string end in while loop, instead of that I have use 0. Does '\0' and 0 same in C?

If yes, then if 0 is in the middle of a string, then printf should end printing the string right there. e.g. printf("%s", "hello how0 are you") should print 'hello how'

int main( )
{
    char s[ ] = "No two viruses work similarly" ;
    int i = 0 ;
    while ( s[i] != 0 )
    {
        printf ( "%c", s[i]) ;
        i++ ;
    }
}

Solution

  • '\0' is the character with the value 0. It is used to terminate strings in C. So, yes, the loop

    while ( s[i] != 0 )
    

    works perfectly fine, although the more conventional way of writing it is

    while ( s[i] != '\0' )
    

    to emphasize that we're working with characters.

    On the other hand, '0' is the character that looks like the number 0, although the value of this character in the ASCII character set is 48. But in any case the value is not 0! So when you write

    printf("%s", "hello how0 are you");
    

    it prints hello how0 are you, because the 0 is an ordinary character, and does not terminate the string. If you wrote

    printf("%s", "hello how\0 are you");
    

    then you would have a null character, and it would terminate the string.