vendredi 29 mai 2015

Printing an array of characters in C with "while"

So here is the working version:

#include <stdio.h>

int main(int argc, char const *argv[]) {
    char myText[] = "hello world\n";
    int counter = 0;
    while(myText[counter]) {
        printf("%c", myText[counter]);
        counter++;
    }
}

and in action:

Korays-MacBook-Pro:~ koraytugay$ gcc koray.c
Korays-MacBook-Pro:~ koraytugay$ ./a.out 
hello world

My question is, why is this code even working? When (or how) does

while(myText[counter])

evaluate to false?

These 2 work as well:

while(myText[counter] != '\0')
while(myText[counter] != 0)

This one prints garbage in the console:

while(myText[counter] !=  EOF)

and this does not even compile:

while(myText[counter] != NULL)

I can see why the '\0' works, as C puts this character at the end of my array in compile time. But why does not NULL work? How is 0 == '\0'?

Aucun commentaire:

Enregistrer un commentaire