user2445311
user2445311

Reputation: 37

Simple C evaluation is turning out wrong

I am stuck with a simple thing but unable to explain the reason for it. Example code scenario is

int e = 0x0000a8e7;
int t = 0xffffffff;

if (e < t) is evaluating to false. Clearly e is +ve and t is -1 and hence e < t should evaluate to false. Why is it still turning to be true. Any ideas ?

Thanks,

Upvotes: 2

Views: 98

Answers (3)

zubergu
zubergu

Reputation: 3706

Just an idea. What size is your int? Check it by printing out sizeof(int).

You make assumption that your int is 32 bit, but if it is 16-bit you overflow t and what happens then is implementation defined, so every machine may work this out differently, and yours did something that made e<t while mine didn't.

Upvotes: 1

dreamlax
dreamlax

Reputation: 95385

You could be encountering implementation-defined behaviour. This means that your code is legal but that each implementation (i.e. each compiler) may perform in different ways. Here are the relevant excerpts from the C specification:

Section 6.7.8 paragraph 11

The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

Section 6.3.1.3 paragraph 3

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

If, in your implementation, int is 32-bit, then 0xffffffff is too large to fit into a 32-bit int (which can hold up to 2,147,483,647, but 0xffffffff = 4,294,967,295).

Upvotes: 1

Aki Suihkonen
Aki Suihkonen

Reputation: 20077

There are two alternatives:

  • sizeof(int) > 4

    (43239 < 4294967295) == true

  • sizeof(int) == 2, where this particular implementation defined behavior occurs

    ( -22297 < -1) == true

Upvotes: 1

Related Questions