What is the difference between a macro and a const in C++?

前端 未结 7 1663
长情又很酷
长情又很酷 2020-12-01 02:08

I was asked this question in a technical interview:

What is the difference between a const and a macro in C++?

My a

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 02:52

    define can be redefine , but const will be cause compiler error:

    sample: source : main.cpp

    #define int_constance 4
    #define int_constance 8 // ok, compiler will warning ( redefine macro)
    
    const int a = 2;
    const int a = 4; // redefine -> error
    
    int main(int argc, char** argv)
    {
       std::cout << int_constance ; // if remove second #define line, output will be 8
    
       return 0;
    }
    

提交回复
热议问题