O
Old Wolf
Schüle Daniel said:Hello Newsgroup,
I was thinking about integer literals and what default types they get
and how they behave when applied to shift operator
Buy the C++ standard, it answers all of your questions
assume sizeof(int) == sizeof(unsigend int) = 4
int ii = -1024;
cout << (ii>>1) << endl; // -512
cout << (ii>>2) << endl; // -256
cout << (-4>>1) << endl; // -2
cout << (-4>>2) << endl; // -1
cout << (-4>>3) << endl; // -1
as one can see -1>>1 doesn't drop to 0
(I would expect it)
is this standard behaviuor?
Right-shifting a negative number is implementation-defined.
(Obviously what's happening is that 111........111 being
right-shifted is still 111.........111).
cout << (1<<31) << endl;
1 has type int, 1 << 31 would set the sign bit
if the expression remains "int" it would be negative
if on the other hand, it would be converted to
"unsigned int" it would be positive
I do get -2147483648 so my compiler chooses it to
remain "int". Again is this standard or impl. defined?
1 << 31 has the value of 2 to the power 31. This value
can't be represented by an int, so the behaviour is
undefined. (This is the same as any other integer overflow).
cout << (1U<<31) << endl;
1U has type "unsigned int", so is 1U<<31 too
I get here 2147483648
I think this is always ok.
2^31 can fit in an unsigned integer, so there's no problem here.
cout << typeid(0x8000000).name() << endl; // i *
cout << typeid(0x80000000).name() << endl; // j **
gcc (GCC) 4.0.2
i means int, j means unsigned int
I always thought that literals like 1 or 100
are always "int" unless explicitelly marked as 1U or 1UL or 1ULL
but what I see here is that compiler puts ** in "unsigned int".
2.13.1#2 says:
If it is octal or hexadecimal and has no suffix, it has the
first of these types in which its value can be represented:
int, unsigned int, long int, unsigned long int.
0x8000000 (2^27) fits in an int, so it is an int.
0x80000000 (2^31) does not fit in an int but does fit in an
unsigned int, so it is an unsigned int.
(If it wouldn't do it, we would get negative number.)
2^31 is a large positive number. It is never negative. Many
people get this wrong. You might get a negative number as
the result of implementation-defined behaviour when you try
and assign this large positive number, to a signed int that
cannot hold such a large number.