Cant i store 4294967295 in unsigned int ? Int is 4 bytes on my machine

前端 未结 3 697
青春惊慌失措
青春惊慌失措 2021-01-29 10:43

Why am i getting 0 ?? And compiler warning:

format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long unsigned int’

3条回答
  •  花落未央
    2021-01-29 11:30

    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;
    }
    

提交回复
热议问题