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

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



> 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 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).


  


Reply to: