Q. What is the output of this C code?

Code:
#include <stdio.h>
int main()
{
   char chr;
   chr = 128;
   printf("%d\n", chr);
   return 0;
}
  • (A) 128
  • (B) -128
  • (C) Depends on the compiler
  • (D) None of the mentioned
πŸ’¬ Discuss
βœ… Correct Answer: (B) -128
Explanation:

In C, char is typically a signed data type unless explicitly declared as unsigned char. The range of a signed char is -128 to 127 (for 8-bit systems).

What happens when chr = 128; ?

  1. 128 is out of the valid range of a signed char (-128 to 127).
  2. Since char is signed by default, 128 undergoes integer overflow (wrap-around behavior).
  3. The value stored in chr becomes -128 if char is signed.

However, the output depends on the compiler settings:

  • If char is signed (default in most compilers) β†’ Output: -128
  • If char is unsigned β†’ Output: 128

Thus, the output depends on the compiler and its default char behavior.

Explanation by: Mr. Dubey

In C, char is typically a signed data type unless explicitly declared as unsigned char. The range of a signed char is -128 to 127 (for 8-bit systems).

What happens when chr = 128; ?

  1. 128 is out of the valid range of a signed char (-128 to 127).
  2. Since char is signed by default, 128 undergoes integer overflow (wrap-around behavior).
  3. The value stored in chr becomes -128 if char is signed.

However, the output depends on the compiler settings:

  • If char is signed (default in most compilers) β†’ Output: -128
  • If char is unsigned β†’ Output: 128

Thus, the output depends on the compiler and its default char behavior.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
274
Total Visits
πŸ“½οΈ
4 y ago
Published
πŸŽ–οΈ
Akash Lawaniya
Publisher
πŸ“ˆ
93%
Success Rate