Why am i getting 0 ?? And compiler warning:
format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long unsigned int’
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
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;
}