Question

I was looking through C++ Integer Overflow and Promotion, tried to replicate it, and finally ended up with this:

#include <iostream>
#include <stdio.h>

using namespace std;

int main() {
    int i = -15;
    unsigned int j = 10; 
    cout << i+j << endl; // 4294967291
    printf("%d\n", i+j); // -5 (!)
    printf("%u\n", i+j); // 4294967291

    return 0;
}

The cout does what I expected after reading the post mentioned above, as does the second printf: both print 4294967291. The first printf, however, prints -5. Now, my guess is that this is printf simply interpreting the unsigned value of 4294967291 as a signed value, ending up with -5 (which would fit seeing that the 2's complement of 4294967291 is 11...11011), but I'm not 100% convinced that I did not overlook anything. So, am I right or is something else happening here?

Was it helpful?

Solution

Yes, you got it right. That's why printf() is generally unsafe: it interprets its arguments strictly according to the format string, ignoring their actual type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top