cfor-loopcastingoutputunsigned-char

How come the output of this C program is 1?


#include <stdio.h>

int main() {
    unsigned char c = (int) 0.54;
    for(; c++; printf("%d", c));

    printf("%d", c);
    return 0;
}

And when I run the program the output is displayed as 1

How can the output be 1? Thanks in advance


Solution

  • In the first line- unsigned char c=(int)0.54; char actually stores the ASCII code of the character so in another way it's an integer which stores the data in this way : The compiler converts the number stored into the character from decimal number system to binary number system and takes into consideration only the first 8 bits from the right of that number represented in binary.(we don't need to consider the case of negative numbers since you use an unsigned char)-so as a result the variable c takes 0 as value at the end of this line.

    For the second line of your code- for(;c++;printf("%d",c)); : so we have a for loop ( for (INITIALIZATION; CONDITION; AFTERTHOUGHT))

    ** In the INITIALIZATION part , Leaving this empty is fine, it's just equivalent that you have already initialized the variable that you are going to use as loop variable .

    ** In the CONDITION part , c++ is equivalent to c++!=0. It keeps the for loop running until c++==0.(in your case c is initialized by 0 , so we will have c++=0 and the program immediately exits the for loop).

    ** In the AFTERTHOUGHT part , The printf is run at the end of each iteration but doesn't change the value of c.(since the condition c++!=0 is not verified the code will not write the iteration, so it will not pass to printf)

    printf("%d",c); will display 1 ( c++ in your loop is used as condition and in the same time to increment variable c by 1 ; c++ post-increment operator uses the principle 'use-then-change' so , c is incremented by 1 exactly after exiting the for loop , and c becomes equal to 1).