Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer promotion, signed/unsigned, and printf

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?

like image 539
rainer Avatar asked Mar 26 '13 16:03

rainer


1 Answers

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.

like image 122
Angew is no longer proud of SO Avatar answered Sep 25 '22 20:09

Angew is no longer proud of SO