unsigned short comparison

P

Paul Edwards

I have the following C program:

#include <stdio.h>

int main(void)
{
unsigned short x = 32768, y=16384;

if (x > y)
{
printf("greater\n");
}
else
{
printf("smaller\n");
}
return (0);
}

And when run on an MVS mainframe using the GCC
compiler, it prints "smaller". When run on the PC it
prints "greater". Here is the generated assembler:

00004C D201 D05C C072 0005C 000B8 42 MVC 92(2,13),=H'-32768'
000052 D201 D05E C074 0005E 000BA 43 MVC 94(2,13),=H'16384'
000058 482D 005C 0005C 44 LH 2,92(13)
00005C 492D 005E 0005E 45 CH 2,94(13)

I think the generated code is wrong. It needs to do a
logical compare instead of an aritmetic compare.

But I have one question. Is the above C program
guaranteed to produce "greater"? I was thinking
that maybe the unsigned short was promoted to a
signed int for the comparison and that in the
process the negative value was used. I tried adding
(unsigned) in front of x and y in "x > y" but it didn't
change the generated code.

Thanks. Paul.
 
E

Eric Sosman

Paul said:
I have the following C program:

#include <stdio.h>

int main(void)
{
unsigned short x = 32768, y=16384;

if (x > y)
{
printf("greater\n");
}
else
{
printf("smaller\n");
}
return (0);
}
[...]

But I have one question. Is the above C program
guaranteed to produce "greater"? I was thinking
that maybe the unsigned short was promoted to a
signed int for the comparison and that in the
process the negative value was used. [...]

Yes, the operands are promoted for comparison.
The promoted type is implementation-dependent:

- If `signed int' can represent all possible values
of `unsigned short', the promotion is to `signed int'

- Otherwise, the promotion is to `unsigned int'

Either way, the promotion preserves the original values:
the promoted values do not become negative, and the
program should print "greater."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,087
Latest member
JeremyMedl

Latest Threads

Top