This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: -sizeof()


On Thu, Nov 18, 2004 at 01:51:32AM +0100, Jan Ringo? wrote:
> Hello, I am not a C++ guru, but this thing looks weird.
> I have following two codes:
> 
> __int64 a = -4;
> printf ("%016I64x\n", a); // prints fffffffffffffffc
> 
> __int64 b = -sizeof(int);
> printf ("%016I64x\n", b); // prints 00000000fffffffc
> 
> Correct me if I am wrong, but shouldn't they return the same value (the 
> first one)??
> I thought that sizeof is evaluated before converting to __int64 (long 
> long)...

I am not certain about C++, but in C the result you see is correct.

It is not a question of when sizeof is evaluated but of signed vs.
unsigned operands.  The type of '4' is signed int. The type of
'sizeof(int)' is size_t (which is equivalent unsigned int on your
system apparently.)

-X, where X is an expression with type unsigned int, also has type
unsigned int, and this is where things change from where you expected.

So '-sizeof(int)' has type unsigned int with the value 0xfffffffc on
your system. Since this fits into a long long no conversion is made
when it is assigned to the variable b.

If you change 'sizeof(int)' to '(int)sizeof(int)' you should get the
same value for both cases (the first one).
(Or if you change  '4' to '(unsigned int)4' you should get the second
value for both cases.)



-- 
<Insert your favourite quote here.>
Erik Trulsson
ertr1013@student.uu.se


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]