"Mark Allums" <m...@allums.com> writes:

>> Is this OK or is this a bug, when the wariable 'n' is
>> initializing by negative value? There no any warning.
>> Is this normal? I know that value -5 is converted
>> to unsigned but probably this should by printed a warning,
>> when this is a constant value. What do you think about this?
>> 
>> 
>> // prog.cpp
>> #include <iostream>
>> using namespace std;
>> 
>> 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)

> I cannot speak to the C++11 standard because ISO/ANSI are not asking a
> reasonable price for the specification docs, and I can't afford the
> price.
>
> A good compiler *may* warn you about this, but it may not do so by
> default.  You may have to turn the warnings on.  Note:  gcc's -Wall is
> tricky.  You may still not get what you expect.
>
> This kind of type shenanigan is allowed in C/C++ because of silent
> standard conversions.  A strongly-(enough)-typed language will not
> permit conversions to or from signed<->unsigned without a cast or a
> conversion function.  C/C++ allows this because there is no loss of
> significant digits (precision).


-- 
To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org 
with a subject of "unsubscribe". Trouble? Contact listmas...@lists.debian.org
Archive: http://lists.debian.org/1btxr0kav5....@snowball.wb.pfeifferfamily.net

Reply via email to