Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given this code snippet, is the output CPU dependent or not?

Tags:

c

void main() {

        if(-1 > 0U)
                printf("True\n");
        else
                printf("False\n");
}

Is it processor-dependent (big endian/little endian)?

like image 488
SeasonedNoob Avatar asked Dec 25 '22 14:12

SeasonedNoob


2 Answers

From C99 6.3.1.8 :

[...] Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Because int and unsigned int have the same conversion rank (see 6.3.1.1), -1 will be converted to unsigned int. As per 6.3.1.3, the conversion result will be (-1 + UINT_MAX + 1) % (UINT_MAX + 1) (arithmetically spoken) which is obviously UINT_MAX and thus greater than 0.

The conclusion is that the C standard demands (-1 > 0U) to be true.

like image 76
Brave Sir Robin Avatar answered Mar 17 '23 03:03

Brave Sir Robin


A piece of code is Endian-Dependent only if it accesses variable x using a pointer whose type is smaller in size than the type of x.

For example:

int   x = 0x12345678;
char* p = (char*)&x;
char  c = p[0]; // 0x12 on BE and 0x78 on LE

Please note the emphasis on "only if", in opposed to "if and only if".

Hence, some examples may still work the same on BE and on LE:

struct s {int a; int b;} x = {0x11223344,0x55667788};
int* p = (int*)&x;
int  i = p[0]; // 0x11223344 in both cases

Note:

Bit-field structures may be compiled differently for BE and for LE.

But this can be referred to as a compiler-dependency rather than as an architectural-dependency.

like image 37
barak manos Avatar answered Mar 17 '23 04:03

barak manos