Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can I get away with not declaring int with signed?

In C, signed integers like -1 are supposedly supposed to be declared with the keyword signed, like so:

signed int i = -1;

However, I tried this:

signed int i = -2;
unsigned int i = -2;
int i = -2;

and all 3 cases print out -2 with printf("%d", i);. Why?

like image 940
George Newton Avatar asked Jan 28 '26 11:01

George Newton


1 Answers

Since you confirmed you are printing using:

printf("%d", i);

this is undefined behavior in the unsigned case. This is covered in the draft C99 standard section 7.19.6.1 The fprintf function which also covers printf for format specifiers, it says in paragraph 9:

If a conversion specification is invalid, the behavior is undefined.248)[...]

The standard defined in section 3.4.3 undefined behavior as:

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

and further notes:

Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

Finally, we can see that int is the same as signed int. We can see this by going to section 6.7.2 Type specifiers, in paragraph 2 it groups int as follows:

int, signed, or signed int

and later on says in paragraph 5 says:

Each of the comma-separated sets designates the same type, except that for bit-field[...]

like image 84
Shafik Yaghmour Avatar answered Jan 31 '26 04:01

Shafik Yaghmour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!