This very simple code:
#include <iostream>
using namespace std;
void exec(char* option)
{
cout << "option is " << option << endl;
if (option == "foo")
cout << "option foo";
else if (option == "bar")
cout << "opzion bar";
else
cout << "???";
cout << endl;
}
int main()
{
char opt[] = "foo";
exec(opt);
return 0;
}
generate two warning: comparison with string literal results in unspecified behaviour.
Can you explain why exactly this code doesn't work, but if I change
char opt[]
to
char *opt
it works, but generates the warning? Is it related to the termination? What is the difference between the two declaration of opt? What if I use const qualifier? The solution is to use std::string?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…