Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

C

Name: Anonymous 2011-03-12 1:32

Hi /prog/

I just notice this strange thing in C:

int a[4];
#define n (sizeof(a) / sizeof(a[0]))
int d = n;

if (-1 < n) {
    printf("yup\n");
}

if (-1 < d) {
    printf("cuack\n");
}

Why is that it doesn't print "yup"?

Name: Anonymous 2011-03-12 2:07

I'm going to go out on a sleep-deprived limb and guess it has something to do with formally declaring and initializing d to constraint whatever is in n, whereas n may not even have a representable value before that.

Which version of C are we talking about?

Name: Anonymous 2011-03-12 2:13

I am using gcc, with sizeof(int) produces the dame result.
if (-1 < sizeof(int)) {
    printf("yup\n");
}

Name: Anonymous 2011-03-12 8:03

Maybe it performs unsigned comparison, perhaps size_t up-casts it.

Name: Anonymous 2011-03-12 8:13

sizeof(int) is unsigned.

if (-1 < (int)sizeof(int)) {
    printf("yup\n");
}

works.

I'm guessing but:

-1 in twos complement would be 1 << sizeof(int) (If I remember correctly).

sizeof(int) would be 4 (usually) unsigned or otherwise.

Could explain why -1 > sizeof(int).

Name: Anonymous 2011-03-12 8:15

>>5
I mena
1 << sizeof(int) * CHAR_BIT

Name: Anonymous 2011-03-12 8:30

As always when macros are giving an unexpected result, look at the preprocessed source and be enlightened.

Name: Anonymous 2011-03-22 22:58

gcc (3.4.4) does this and the preprocessed results don't give anything away
even with all -O0, the first branch and call to printf is missing from the generated assembly
are the optimization flags buggy?

Name: Anonymous 2011-03-23 8:16

>>6
That would be 0.

Name: Anonymous 2011-03-23 12:40


Don't change these.
Name: Email:
Entire Thread Thread List