0

I've just a great programming puzzle. Why is to same?

#include <stdio.h>
#include <limits.h>

int main(int argc, char *argv[])
{
  unsigned int x = ULONG_MAX;
  char y = -1;   
  if (x == y) printf("That is same.");  

  return 0;
}

I think that unsigned int is converted to signed char, and thus it will be -1. It may be a standard for comparison of signed and unsigned type. I don't know...

RePRO
  • 265
  • 6
  • 18
  • 2
    Is this homework? Please use the [tag:homework] tag if so. – T.J. Crowder May 02 '12 at 18:09
  • this is a dup of http://stackoverflow.com/questions/6636793/what-are-the-general-rules-for-comparing-different-data-types-in-c – nate_weldon May 02 '12 at 18:13
  • This is not a puzzle, this is totally expected behaviour if you know what two's complement arithmetic is. – Daniel Kamil Kozar May 02 '12 at 18:14
  • How can someone voteup to homework? That is very difficult code why does it work like that. :-) wildplasser: Maybe. I'm sorry, but I'm not oriented in standart. ;-) – RePRO May 02 '12 at 18:14
  • 1
    BTW: You don't compare *variables*; you compare **values**. Values have types, too, partially inherited from the variables that they stem from; partially shaped by the operators that they are submitted to. The syntax probably says `expr == expr`, but expressions have values and types, too. – wildplasser May 02 '12 at 18:15

2 Answers2

2

In a tiff between signed char and unsigned int, unsigned int wins!

Its like this

Size does matter

Here -1 will be converted to unsigned int which is ULONG_MAX and hence if() condition is true.

In C, size does matter. Variables are always converted to the highest size among them.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
  • For completeness : since `y` is a `char`, which is signed, the value is sign-extended to the `unsigned int`, so we get a `11...11` - which is exact to `ULONG_MAX`. – Daniel Kamil Kozar May 02 '12 at 18:17
  • Gives me values -1 and -1. Why? – RePRO May 02 '12 at 18:45
  • @RePRO I think you are printing out the values using `printf` `%d`. And hence you see `-1`s. `%d` interprets the value as a signed integer which converts `ULONG_MAX` to `-1`. Number representation is the same but interpretations will differ. `==` favors `unsigned int` whereas `%d` favors `signed int` – Pavan Manjunath May 02 '12 at 19:04
1

Many years ago, I learned a couple of things. One of them was compare like types.

I would either cast the char to an unsigned int if the unsigned int's value is greater than sizeof char. Or cast the other way if the unsigned int's values are to be restricted to a sizeof char. In that way, you are telling the compiler how you are comparing the values, and it will help maintainers as well.

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131