[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

RE: Is this OK in C++ and C?



> Joe Pfeiffer :


int main()
{
const unsigned int n = -5;

cout << "The variable n is: " << n << endl;

return 0;
}

Results:
$ g++ -Wall -W  prog.cpp -o prog
$ ./prog
The variable n is: 4294967291


> > This is expected behavior, but not defined by the standard because the
> > result is not portable.  That is, a rollover value will occur, but it
> > could vary depending on the width of an int, and possibly by the
> > binary representation.  As far as I know all systems that Debian with
> > gcc runs on are two's complement, but still...

 
> I believe it is indeed defined behavior.



>   6.3.1.3 Signed and unsigned integers
> 1 When a value with integer type is converted to another integer type
other
> than _Bool, if
>   the value can be represented by the new type, it is unchanged.
> 2 Otherwise, if the new type is unsigned, the value is converted by
> repeatedly adding or
>   subtracting one more than the maximum value that can be represented in
> the new type
>   until the value is in the range of the new type.49)
> 

Yes, defined conversion, but not a defined *exact* result; that is, the
result is system dependent. 

So, yeah.  


> > This kind of type shenanigan is allowed in C/C++ because of silent
> > standard conversions. 




Reply to: