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 \0 termination? What is the difference between the two declaration of opt? What if I use const qualifier? The solution is to use std::string?
Looks like you came from Java/C# :) In C++ string is just a pointer to memory where characters are stored and with null char at the end. If strings "look" equal they may point to different areas in memory and will not be equal. to check equality either use C++'s class std::string or C function strcmp .
char arrays or char pointers aren't really the same thing as string class objects in C++, so this
Doesn't compare the string
option
to the string literal "foo" it compares the address ofoption
with the address of the string literal "foo". You need to use one of the many string comparison functions if you want to know if the option is the same as "foo".strcmp
is the obvious way to do this, or you can usestd::string
instead ofchar*
You can use
==
operator to compare strings only if you usestd::string
(which is a good practice). If you use C-style char*/char[] strings, you need to use C functionsstrcmp
orstrncmp
.You can also use the
std::string::operator ==
to comparestd::string
with a C string: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
For C++ I would use the std::string solution:
std::string knows how to create itself out of char[], char*, etc, so you can still call the function in these ways, too.