gokul goku
gokul goku

Reputation: 35

how do char pointers work with while loop

In the while loop when *s is mentioned it means the value at the address contained in s, so in the first case, the value will be 'a',

my question is how will while loop checks it, does it checks the ASCII value of the characters to check the condition is true or false ..are some other way?

main()
{
   char str[] = "abcd" ;
   char *s = str;
   while(*s)
       printf ("%c",*s++) ;
}

Upvotes: 1

Views: 914

Answers (2)

Dustin K
Dustin K

Reputation: 169

while(conditon) in C/C++ code will execute if condition != 0

Since it is a dereferenced char*, this means it is a 1 byte value. Which ranges from 0-255.

Since the first value is 'a' this means it will print this table from values 'a'(61) to 'nbsp' (255) after 255 the char value will overflow to '0' or NULL character at which point the while(condition) will evaluate to false and the program will end.

enter image description here

Upvotes: 1

Julio P.C.
Julio P.C.

Reputation: 330

When you declare a string variable like

char str[] = "abcd";

it's like declaring str[5] = "abcd\0";

So, in your while loop, it first checks the value of *s, which is 'a', that translates to 97 on the ascii table. Then you print the current value inside the *s pointer, and then increase the pointer by 1, which leads to the next character. When you reach the \0, the loop exits, because \0 is equal to 0;

Upvotes: 4

Related Questions