Compiler gives warning when printing the address of a variable

前端 未结 3 1020
一整个雨季
一整个雨季 2021-01-29 05:36

I made a very simple program to print the address of two variables.

#include

int main()
{
    int a,b;
    printf(\"%u\\n%u\",&a,&b);
            


        
3条回答
  •  长情又很酷
    2021-01-29 06:30

    %p is the correct format specifier to print addresses:

    printf("%p\n%p",(void*)&a, (void*)&b);
    

    The C standard requires that the argument corresponding to %p should be of type void*. So the casts are there.

    C11, Reference:

    p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

    Using incorrect format specifier is undefined behavior. A compiler is not required to produce any diagnostics for undefined behaviors. So both are gcc and clang are correct.

    GCC 5.1 does produce warnings on my system without any additional options. And GCC godbolt produces warnings with stricter compiler options: -Wall -Wextra. In general, you should compile with strictest compiler options.

提交回复
热议问题