Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typecasting to unsigned in C

Tags:

c++

c

casting

int a = -534;
unsigned int b = (unsigned int)a;
printf("%d, %d", a, b);

prints -534, -534

Why is the typecast not taking place?

I expected it to be -534, 534


If I modify the code to

int a = -534;
unsigned int b = (unsigned int)a;
if(a < b)
  printf("%d, %d", a, b);

its not printing anything... after all a is less than b??

like image 875
Lazer Avatar asked Mar 01 '10 12:03

Lazer


1 Answers

Because you use %d for printing. Use %u for unsigned. Since printf is a vararg function, it cannot know the types of the parameters and must instead rely on the format specifiers. Because of this the type cast you do has no effect.

like image 192
Tronic Avatar answered Nov 02 '22 23:11

Tronic