Why am i getting 0 ?? And compiler warning:
format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long unsigned int’
Assuming an int
is 4 bytes and you have 8 bit bytes, then int
is 32 bits wide. Subsequently a signed int
(if negatives are represented in 2's complement) has a range of -2147483648 to 2147483647 while unsigned int
has a range of 0 to 4294967295.
The value 4294967296 in binary is 1 00000000 00000000 00000000 00000000
. This is 33 bits. So 4294967296 is too big for this type.
I am back after long time (obviously) to this question, and I am not sure why everyone thinks OP meant to store 4294967296
when he wanted to store 4294967295
as asked in the question, maybe OP changed the question later, and no one bothered to re-answer. Now, back to question.
You can store 4294967295
in unsigned int
, but the problem is in your printing, you are doing printf("%d", 4294967295)
which means print 4294967295
as a signed int
, but the number 4294967295
cannot be stored in signed int
, so, narrowing conversion happens.
You need to print the unsigned int
that you've got with %u
rather than %d
.
#include <stdio.h>
int power(int base, int pow);
int main(){
printf("Size of unsigned int: %d\n", sizeof(unsigned int));
unsigned int the_number = power(2, sizeof(int)*8)-1;
printf("Wrongly printed: %d\n", the_number);
printf("Correctly printed: %u\n", the_number);
return 0;
}
int power(int base, int on) {
int pf = 1;
for (int i = 0; i < on; i++) {
pf *= base;
}
return pf;
}
If your int
or unsigned int
is 32-bits, neither can store the value 4294967296
since this is 2**32
which would require a 64-bit type.
Even uint32_t
can only store the max value 2**32 - 1
so your value is just 1
out of range.
But int32_t
can store the max positive value 2**31 - 1
so the signed type is even further off.