conversion from unsigned

L

Lars Amsel

Hi,

I am a bit confused about some C++ code

unsigned l = 1;
cout << -l << " " << pow(2., -l-1.) << endl;

I expected

$>-1 0.25

I got

$>4294967295 inf

OK. It's clear that their is a underflow in the unsigned l. I expected a
auto conversion by the compiler to int. When I change the code to

unsigned preL = 1;
int l = -preL;
cout << -l << " " << pow(2., -l-1.) << endl;

everything works fine. Is that well defined c++ behaviour or is it a bug
in g++ (version 3.3.x)?

Cheers

Lars
 
R

Rob Williscroft

Lars Amsel wrote in in
comp.lang.c++:
Hi,

I am a bit confused about some C++ code

unsigned l = 1;
cout << -l << " " << pow(2., -l-1.) << endl;

I expected

$>-1 0.25

Basic arithmatic in C++, dosen't do type conversion's so
-(ubsigned)1, has type unsigned, if nessacery the compiler
will "widen" types *bofore* doing the arithmatic:

long l = 1; int i = 2;

( l + i ) will have type long and before the addition i will
be "widend" from int to long.

unsigned int is "wider" than int, there is no real logic to it
but one has to be wider than the other, else we wouldn't have
a clue whats going on.
I got

$>4294967295 inf

(unsigned)-1 is required to be UINT_MAX (4294967295U on your
platform).
OK. It's clear that their is a underflow in the unsigned l.

Nope unsigned uses modulo arithmatic, values wrap around from
0 to UINT_MAX ( math is done modulo (UINT_MAX + 1) ).
I expected a
auto conversion by the compiler to int. When I change the code to

unsigned preL = 1;
int l = -preL;
cout << -l << " " << pow(2., -l-1.) << endl;

everything works fine. Is that well defined c++ behaviour or is
it a bug in g++ (version 3.3.x)?

Its well defined (other than the actual value 4294967295 (UINT_MAX)
is implemetation defined).

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top