String literal comparison

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;
}

generates two warnings: comparison with a string literal leads to unspecified behavior.

Can you explain why this particular code is not working, but if I change

char opt[]

to

char *opt

Does it work, but generates a warning? Is this related to the termination \ 0? What is the difference between two opt ads? What if i use const constructor? The solution is to use std :: string?

+4
source share
5 answers

char arrays or char pointers are actually not the same as string class objects in C ++, so this

if (option == "foo")

option "foo" , option "foo" . , , , "foo" . strcmp - , std::string char*

+12

== , std::string ( ). C

std::string::operator == std::string C:

std string foo = "foo";
const char *bar = "bar";

if (foo == bar) 
   ...
+2

, , , , .

, char *, , "" ( , - , , ).

char opt [] , opt (, ), .

Renze

+2

, Java/#:) ++ - , char . "" , . ++ std::string, C strcmp.

0

++ std::string :

#include <iostream> 
#include <string>

using namespace std; 

void exec(string option) 
{ 
    cout << "option is " << option << endl; 
    if (option == "foo") 
        cout << "option foo"; 
    else if (option == "bar") 
        cout << "option bar"; 
    else 
        cout << "???"; 
    cout << endl; 
} 

int main() 
{ 
    string opt = "foo"; 
    exec(opt);

    exec("bar");

    char array[] = "other";
    exec(array);
    return 0; 
} 

std::string , char [], char * .., .

0

Source: https://habr.com/ru/post/1737502/


All Articles