Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use a+b as an argument for printf in C

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading