c - Printing an array of characters with "while" -


so here 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 code working? when (or how)

while(mytext[counter]) 

evaluate false?

these 2 work well:

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

this 1 prints garbage in console:

while(mytext[counter] !=  eof) 

and not compile:

while(mytext[counter] != null) 

i can see why '\0' works, c puts character @ end of array in compile time. why not null work? how 0 == '\0'?

as last question,

but why not null work?

usually, null pointer type. here, mytext[counter] value of type char. per conditions using == operator, c11 standard, chapter 6.5.9,

one of following shall hold:

  1. both operands have arithmetic type;
  2. both operands pointers qualified or unqualified versions of compatible types;
  3. one operand pointer object type , other pointer qualified or unqualified version of void; or
  4. one operand pointer , other null pointer constant.

so, tells, can only compare pointer type null pointer constant ## (null).

after that,

when (or how) while(mytext[counter]) evaluate false?

easy, when mytext[counter] has got value of 0.

to elaborate, after initialization, mytext holds character values used initialize it, "null" @ last. "null" way c identifies string endpoint. now, null, represented values of 0. so, can say. when end-of-string reached, while() false.

additional explanation:

  • while(mytext[counter] != '\0') works, because '\0' representation of "null" used string terminator.

  • while(mytext[counter] != 0) works, because 0 decimal value of '\0'.

above both statements equivalent of while(mytext[counter]).

  • while(mytext[counter] != eof) not work because null not eof.

reference: (#)

reference: c11 standard, chapter 6.3.2.3, pointers, paragraph 3

an integer constant expression value 0, or such expression cast type void *, called null pointer constant.

and, chapter, 7.19,

null
expands implementation-defined null pointer constant


note: in end, this question , realted answers clear confusion, should have any.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -