comparison between string literal

前端 未结 4 888
后悔当初
后悔当初 2020-11-30 12:25

This very simple code:

#include 

using namespace std;

void exec(char* option)
{
    cout << \"option is \" << option << e         


        
4条回答
  •  -上瘾入骨i
    2020-11-30 12:36

    The reason why it doesn't work is because the comparison does not compare strings, but character pointers.

    The reason why it may work when you use char* is because the compiler may decide to store the literal string "opt" once and reuse it for both references (I am sure I have seen a compiler setting somewhere that indicates whether the compiler does this).

    In the case of char opt[], the compiler copies the string literal to the storage area reserved for the opt array (probably on the stack), which causes the pointers to be different.

    Renze

提交回复
热议问题