2

I'm fairly new to coding and had a question regarding the output of a program I've recently encountered. Here's the code:

#include <stdio.h>

int main(void) {
    unsigned char x = 16;
    x = x * 16;

    if (x) {
        printf("True.\n");
    }
    else {
        printf("False.\n");
    }

    return 0;
}

The output of this program is apparently "False.\n". I have two questions regarding this:

  1. What does it mean if the argument of a conditional statement is simply a variable?
  2. Why is the output "False.\n"?

Thank you! Any word of advice or tips are greatly appreciated.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Sean
  • 2,890
  • 8
  • 36
  • 78
  • 5
    Please read any basic C book or tutorial. Those are better resources for C fundamentals than Stackoverflow. But in summary, 0 is false in C and anything else is true. And the result is false because `16*16` overflows a `char` and hence the result is 0. – kaylum May 16 '17 at 01:34
  • 5
    @kaylum it's `unsigned char`. And out-of-range assignment (not overflow) as the operands of `*` are promoted to `int`. – M.M May 16 '17 at 01:36
  • 2
    Possible duplicate of [if statement integer](http://stackoverflow.com/questions/14646718/if-statement-integer) – Bernhard Barker May 16 '17 at 01:43
  • Try `printf("%d\n", (int)x);` You will find it prints 0. – anonymoose May 16 '17 at 01:56

2 Answers2

4
unsigned char x = 16;

x is an unsigned char, which is in range [0, 255].

x = x * 16;

the C99 standard(§6.2.5/9) states

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

x equals 16 * 16 % 256 = 256 % 256 = 0.

if (x) {

For values not equal to zero this statement should be true. For values equal to zero this statement should be false, and this was your case.

luoluo
  • 5,353
  • 3
  • 30
  • 41
3

x * 16 is not overflow.

x has the value of 16. As part of the multiplication, unsigned x is converted to int and code does an int * int whose product is 256 - no overflow.

Now int 256 is assigned to an unsigned char. When some unsigned integer type is assigned a value outside its range, the value is reduced/increased in "max + 1" steps, or 256 until it is in range as the max value of unsigned char on OP's platform is 255. Again, no overflow. The value is 0.

What does it mean if the argument of a conditional statement is simply a variable?
Why is the output "False.\n"?

The if(something) is false if something equates to 0, all else is true.

if (x) {
//
if (0) {
//
if (false) {
    ... // irrelevant
} else {
    printf("False.\n");
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256