static const vs #define

前端 未结 11 1015
醉话见心
醉话见心 2020-11-22 13:01

Is it better to use static const vars than #define preprocessor? Or maybe it depends on the context?

What are advantages/disadvantages for

11条回答
  •  无人共我
    2020-11-22 13:10

    #define can lead to unexpected results:

    #include 
    
    #define x 500
    #define y x + 5
    
    int z = y * 2;
    
    int main()
    {
        std::cout << "y is " << y;
        std::cout << "\nz is " << z;
    }
    

    Outputs an incorrect result:

    y is 505
    z is 510
    

    However, if you replace this with constants:

    #include 
    
    const int x = 500;
    const int y = x + 5;
    
    int z = y * 2;
    
    int main()
    {
        std::cout << "y is " << y;
        std::cout << "\nz is " << z;
    }
    

    It outputs the correct result:

    y is 505
    z is 1010
    

    This is because #define simply replaces the text. Because doing this can seriously mess up order of operations, I would recommend using a constant variable instead.

提交回复
热议问题