C
C
coder2021-09-16 11:01:03
C++ / C#
coder, 2021-09-16 11:01:03

Why does this code work wrong?

Why is the result of this code not 0 but -1? Is the data type broken?

#include <stdio.h>

int main() {
    unsigned cash = 0;
    --cash;

    printf("%d", cash);

    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-09-16
@RomanSamets

Because %d treats the passed value as a signed int.
Supply %u and get the unsigned value of UINT_MAX (0xFFFFFFFF).
But you still won't get zero, operations with unsigned numbers in C are performed modulo (UINT_MAX+1).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question