Home > database >  Use a b as an argument for printf in C
Use a b as an argument for printf in C

Time:11-23

#include <stdio.h>
int main()
{
    char a = 0, b = 0, total = 0;

    a = 120;
    b = 9;

    total = a   b;

    printf("The sum of two numbers are: %d\n", a   b); // 129
    printf("The sum of two numbers are: %d\n", total); // -127

    return 0;
}

The value of 129 is incorrect. I know it has to do with the printf function but don't know why/how. The value of -127 is correct because of an overflow in total.

CodePudding user response:

The value of 129 is incorrect. I know it has to do with the printf function but don't know why/how.

No, it is not incorrect, and it has nothing to do with printf.

In printf("The sum of two numbers are: %d\n", a b);, the operands of are subject to the usual arithmetic conversions defined in C 2018 6.3.1.8. These conversions include the integer promotions, which convert char operands to int operands in normal C implementations.

Thus, in a b, a is converted to int, b is converted to int, and their values are added to produce an int result. That result is 129, which is printed.

The value of -127 is correct because of an overflow in total.

When overflow occurs, the C standard does not define the behavior, so any result would be “correct” in that it is within what the C standard allows. Also, no result (from the program terminating) or any other behavior (such as corrupting other parts of the program) would be “correct” in the same sense.

However, no overflow occurs here. As with the printf, in total = a b;, a and b are converted to int and then added, and the result is again 129. Then 129 is assigned to total. Since total is a char, and the maximum char value in your C implementation is 127, the conversion changes the value. C 2018 6.3.1.3 3 says either the result is implementation-defined or a signal is raised. Your C implementation apparently wraps the result modulo 256, so 129 becomes 129−256 = −127. (For example, GCC documents that this is what it does.)

Then printf("The sum of two numbers are: %d\n", total); passes −127 to printf, which of course prints “-127”.

CodePudding user response:

In firt case a and b are converted to int and then added. The result 129 fits the int

The second case the result of the addition does not fit into the char. It is I believe Implementation defined behaviour. In this case 129 in two's complement 8 bits format is -127.

  •  Tags:  
  • c
  • Related