Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison between string literal

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?

like image 851
Ruggero Turra Avatar asked Nov 28 '22 11:11

Ruggero Turra


1 Answers

char arrays or char pointers aren't really the same thing as string class objects in C++, so this

if (option == "foo")

Doesn't compare the string option to the string literal "foo" it compares the address of option 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 use std::string instead of char*

like image 51
John Knoeller Avatar answered Dec 09 '22 14:12

John Knoeller