Search code examples
cgcc-warning

C Programming type casting and sizeof()


When i type cast and convert an double data type into an int data type and then i try to print that how much size is gonna take it shows me int size but when compiling it gives me the warning (gcc).I am wondering why it's giving me warning and how to get rid of this warning.

i have tried with structs as well but the warning still showing on compiling. cast.c:12:11: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=] printf("%d\n",sizeof(cast)); ~^ %ld

#include <stdio.h>

int main(void){
    double n=0;
    //  int x=0;
    int cast;
    cast = (int) n;
    printf("%d\n",sizeof(cast));
    return 0;
}

i expect to find out why it is showing the warning.


Solution

  • sizeof produces a value of type size_t. A proper way to print it is with the format %zu:

    printf("%zu\n", sizeof cast));
    

    z is a modifier for the size_t type, and u is for unsigned, because size_t is unsigned. (%d is for signed int.)