How can I print the result of sizeof() at compile time in C?

后端 未结 12 1333
星月不相逢
星月不相逢 2020-11-29 20:47

How can I print the result of sizeof() at compile time in C?

For now I am using a static assert (home brewed based on other web resources) to compare the sizeof() re

12条回答
  •  温柔的废话
    2020-11-29 21:30

    //main.cpp
    #include 
    template 
    struct show_size;
    
    void foo()
    {
        show_size();//!!please change `my_type` to your expected
    }
    
    int main()
    {
        return 0;
    }
    

    You can compile this pretty simple code, and during its pre-compilation stage, the compiler will give error, in which the sizeof(my_type) will give concrete value. e.g.:

    g++ main.cpp
    

提交回复
热议问题