unsigned wierdness

T

tobiasoed

Hello!
I have the following piece of code:

#include <stdio.h>

int main(void){

unsigned int u;
int i1, i2;
double d1,d2;

u = 0;

i1 = u - 1;
i2 = (signed int) u - 1;

d1 = u - 1;
d2 = (signed int) u - 1;

printf("i1 = %d, i2 = %d, d1 = %f, d2 = %f\n",i1,i2,d1,d2);
}

and don't understand the output:
tobsbox:~/C$ cc -std=c99 -Wall -W -pedantic unsigned.c && ./a.out
i1 = -1, i2 = -1, d1 = 4294967295.000000, d2 = -1.000000

It looks like u is promoted to signed int for i2 but not d2. Is
this normal or is it a compiler bug?
Tobias
ps: My compiler is
cc (GCC) 3.4.3 20050227 (Red Hat 3.4.3-22.fc3)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is
NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
 
T

tobiasoed

Hello!
I have the following piece of code:

#include <stdio.h>

int main(void){

unsigned int u;
int i1, i2;
double d1,d2;

u = 0;

i1 = u - 1;
i2 = (signed int) u - 1;

d1 = u - 1;
d2 = (signed int) u - 1;

printf("i1 = %d, i2 = %d, d1 = %f, d2 = %f\n",i1,i2,d1,d2);
}

and don't understand the output:
tobsbox:~/C$ cc -std=c99 -Wall -W -pedantic unsigned.c && ./a.out
i1 = -1, i2 = -1, d1 = 4294967295.000000, d2 = -1.000000

Never mind. The whole rhs is done in unsigned arithmetic and gives
-1U which is 4294967295 here. The assignement to i1 'overflows' and
happens to give -1. The assignement to d1 doesn't and preserves the
value. I mistakenly thought that the rhs would all be done in
signed.
Tobias.
 
O

Old Wolf

Never mind. The whole rhs is done in unsigned arithmetic and
gives -1U which is 4294967295 here. The assignement to i1
'overflows' and happens to give -1.

To be precise: since 4294967295 is outside the range of
signed int, the assignment to i1 either gives an
implementation-defined result, or raises an implementation-
defined signal.
 

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,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top