1

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++) ;
}
1
  • A non-zero value means True. Value of a char is basically an integer. The value of a nul character denoting end of string (\0) is zero. The loop stops then.
    – J...S
    Jun 18, 2019 at 5:34

2 Answers 2

4

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;

2
  • do you mean that the *s will be converted to 97 in case of a and then evaluated ? so in that case what will happen if my string contains digit 0 will it check for 0 or its ascii 48?
    – gokul goku
    Jun 18, 2019 at 8:29
  • Yes, that's what I mean. If your code contains something like char str[] = "abc0123"; then every number will also be converted to their respective ASCII values, and then evaluated.
    – Julio P.C.
    Jun 20, 2019 at 3:31
1

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.