-5
#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

Gpine185
  • 44
  • 8
  • The `for` loop's 3rd expression never executes because its 2nd expression evaluates to false because `c` is initialized to 0. Because the 2nd expression executes, `c` becomes 1. – Jeff Holt Apr 26 '22 at 02:27

1 Answers1

0

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).

TheKing
  • 136
  • 9
  • 1
    That first paragraph is wrong. There are no ASCII values involved. Variable `c` stores the value 0 because the numerical value `0` is assigned to it, not the ASCII value of any character. – Gerhardh Apr 26 '22 at 06:33
  • Yes , but i'm trying to explain what char can store in general (it always stores an integer value) – TheKing Apr 26 '22 at 06:40