test
test

Reputation: 451

Hexadecimal constant in C is unsigned even though L suffix

I know this is a simple question but I'm confused. I have a fairly typical gcc warning that's usually easy to fix:
warning: comparison between signed and unsigned integer expressions

Whenever I have a hexadecimal constant with the most significant bit, like 0x80000000L, the compiler interprets it as unsigned. For example compiling this code with -Wextra will cause the warning (gcc 4.4x, 4.5x):

int main()
{
long test = 1;
long *p = &test;
if(*p != 0x80000000L) printf("test");
}

I've specifically suffixed the constant as long, so why is this happening?

Upvotes: 8

Views: 6374

Answers (5)

Nemo
Nemo

Reputation: 71535

The answer to Unsigned hexadecimal constant in C? is relevant. A hex constant with L suffix will have the first of the following types that can hold its value:

long
unsigned long
long long
unsigned long long

See the C99 draft, section [ 6.4.4.1 ], for details.

On your platform, long is probably 32 bits, so it is not large enough to hold the (positive) constant 0x80000000. So your constant has type unsigned long, which is the next type on the list and is sufficient to hold the value.

On a platform where long was 64 bits, your constant would have type long.

Upvotes: 12

David X
David X

Reputation: 4166

Because your compiler uses 32-bit longs (and presumably 32-bit ints as well) and 0x80000000 wont fit in a 32-bit signed integer, so the compiler interprets it as unsigned. How to work around this depends on what you're trying to do.

Upvotes: 1

qoyllur
qoyllur

Reputation: 29

Hex constants in C/C++ are always unsigned. But you may use explicit typecast to suppress warning.

Upvotes: 0

Paul
Paul

Reputation: 141827

It's an unsigned long then. I'm guessing the compiler decides that a hex literal like that is most likely desired to be unsigned. Try casting it (unsigned long)0x80000000L

Upvotes: 0

steve
steve

Reputation: 6020

According to the c standard hex constants are unsigned.

Upvotes: -1

Related Questions