printf get -1 for an unsigned integer

L

lovecreatesbeauty

why does printf get -1 for an unsigned integer?


#include <stdio.h>

int main(void)
{
unsigned int u = 0;

u--;
if (u < 0)
printf("u < 0\n");
else
printf("u >= 0\n");
printf("u: %d\n", u);
return 0;
}

$ cc a.c
$ ./a.out
u >= 0
u: -1
$
 
M

mark_bluemel

why does printf get -1 for an unsigned integer?

It doesn't know how to interpret what you've given it, expect by the
"mask" you specify.
#include <stdio.h>

int main(void)
{
unsigned int u = 0;

u--; [snip]
printf("u: %d\n", u);
[snip]

You lied to printf.

Try reading the manual before posting this sort of nonsense.
 
R

Richard Heathfield

(e-mail address removed) said:
why does printf get -1 for an unsigned integer?

Because you tricked printf. You said you were giving it a signed int,
and it believed you.

Use %u, not %d, to print unsigned ints.
 
K

Keith Thompson

why does printf get -1 for an unsigned integer?


#include <stdio.h>

int main(void)
{
unsigned int u = 0;

u--;
if (u < 0)
printf("u < 0\n");
else
printf("u >= 0\n");
printf("u: %d\n", u);
return 0;
}

$ cc a.c
$ ./a.out
u >= 0
u: -1
$

Because you lied to it. "%d" expects an argument of type int; you
gave it an argument of type unsigned int. Try "%u".

(You're probably seeing that behavior because (unsigned int)-1, or
UINT_MAX, has the same representation as (int)-1 in 2's-complement,
but that's not guaranteed.)
 
M

Martin Ambuhl

why does printf get -1 for an unsigned integer?


#include <stdio.h>

int main(void)
{
unsigned int u = 0;

u--;
if (u < 0)

Because u is unsigned, the above condition is never satisfied
printf("u < 0\n");
else
printf("u >= 0\n");
printf("u: %d\n", u);

Because u is unsigned, printing its value with "%d", specifying a
_signed_ value is an error.
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top