467,889 Members | 1,399 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,889 developers. It's quick & easy.

unsigned short comparison

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
  • viewed: 4730
Share:
1 Reply
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.

Similar topics

19 posts views Thread by MiniDisc_2k2 | last post: by
4 posts views Thread by Anupam | last post: by
10 posts views Thread by Vijay Kumar R Zanvar | last post: by
7 posts views Thread by HH | last post: by
26 posts views Thread by LuB | last post: by
10 posts views Thread by Jim Langston | last post: by
reply views Thread by MrMoon | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.