PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 14, 2022

[FIXED] How come the output of this C program is 1?

 August 14, 2022     c, casting, for-loop, output, unsigned-char     No comments   

Issue

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



Answered By - TheKing
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing