RePRO
RePRO

Reputation: 263

Comparison of two variables

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...

Upvotes: 0

Views: 128

Answers (2)

Pavan Manjunath
Pavan Manjunath

Reputation: 28535

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.

Upvotes: 2

octopusgrabbus
octopusgrabbus

Reputation: 10695

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.

Upvotes: 1

Related Questions