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

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



C lessons today? (There are newsgroups for C and C++ questions, but, why not?)

On Tue, Jan 1, 2013 at 3:33 AM, Zbigniew Komarnicki <cblasius@gmail.com> wrote:
> Is this OK or is this a bug, when the wariable 'n' is
> initializing by negative value? There no any warning.
> Is this normal?

Depends on the compiler and the settings.

> I know that value -5 is converted
> to unsigned

Well, you think you do from some past experience, perhaps, but, no,
that is not what you should expect to happen.

> but probably this should by printed a warning,
> when this is a constant value. What do you think about this?

Rather have warnings when implicit conversions on variables or complex
expressions might lose significance. That's why the compiler allows
some tuning of the warnings and errors returned. (And why the standard
allows the tuning within standard behavior.)

> // prog.cpp
> #include <iostream>
> using namespace std;
>
> int main()
> {
> const unsigned int n = -5;

So, what exactly are you trying to do here?

That could be perfectly valid code in certain cases.

>   cout << "The variable n is: " << n << endl;
>
>   return 0;
> }
>
> Results:
> $ g++ -Wall -W  prog.cpp -o prog

-pedantic is another useful option, not that it helps here.

> $ ./prog
> The variable n is: 4294967291

Well, it looks about right. Lessee,
---------------------------
user@beast;~$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale = 20
2^32 - 5
4294967291
---------------------------

Yep. What you got is what I would expect in most cases on modern hardware.

Were you expecting, perhaps, 18446744073709551611 or 65531?

Perhaps, 2147483643? (What would happen on a ones complement CPU/runtime?)

> Thank you.

Try this code to see if it helps you understand:
----------------------------
int main()
{
const unsigned int n = -5;
char c = n;

  cout << "The variable n is: " << n << " and c is: " << (int) c << endl;
/* etc. */
----------------------------

--
Joel Rees


Reply to: