can anyone crack this?

can anyone tell whats happening here?!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
	unsigned long a = 100000;
	long b = -1;
	if(b>a)
	cout<<"yes"<<endl;
	else
	cout<<"no"<<endl;

	return 0;
}

OUTPUT: yes

thanks in advance!
Yeah "long" is short for "long int", int's don't do negative values instead they set the highest bit to '1' and process the rest of the number in reverse.
you're comparing signed and unsigned types.

What's happening is the compiler is casting to the "larger" type for the comparison. In this case it figures unsigned long is larger.

Therefore if(b>a) is the same as if((unsigned long)b>a)

(unsigned long)b casts a signed negative number (-1) to an indredibly large unsigned number (0xFFFFFFFF) which is larger than 100000

Hence it's printing "yes"
@Computergeek01

ok.. but how does that explain this..
a bit more detail pls...

also.. int stores negative numbers as well rite?
by default int means signed int
@Disch

Why does it do like that..
any logical reason to do like that?
i mean, why is this happenning>>>
(unsigned long)b casts a signed negative number (-1) to an indredibly large unsigned number (0xFFFFFFFF) which is larger than 100000
Because you can't compare a negative integer to an unsigned integer. An unsigned integer can never be equal to -1 because it has no sign (no + or -; it is always positive). The only way to compare an unsigned integer with a signed integer is to cast one of them to the same type as the other one -- as Disch said, unsigned long is larger than long, so the compiler casts the long integer to an unsigned long integer. The value of (unsigned long)-1 is 0xFFFFFFFF. unsigned integer values wrap around, so -1 is equal to 0xFFFFFFFF, -2 is equal to FFFFFFFE, and so on.
@chrisname
woohoo!! understood... thanks pal :)
You're welcome :]
Topic archived. No new replies allowed.