comparison between string literal

Posted by wiso on Stack Overflow See other posts from Stack Overflow or by wiso
Published on 2010-03-18T10:52:10Z Indexed on 2010/03/18 11:21 UTC
Read the original article Hit count: 665

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about literal