By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,497 Members | 1,921 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,497 IT Pros & Developers. It's quick & easy.

unsigned short comparison

P: n/a
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.
Nov 15 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Paul Edwards wrote:
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."

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.