Home > Net >  Undefined Behavior While Comparing two std::string in C [closed]
Undefined Behavior While Comparing two std::string in C [closed]

Time:09-17

i have a simple loop that goes through the elements of a vector and check if that element is equal to some other string or not. The problem is that even when the two strings that i am comparing using == have different value, the if condition is satisfied. I have confirmed the same using gdb. The code that i have is as follows:

for(std::string &curr:myVector)
        {
                        
            std::string temp = "Not Value";
            std::cout<<" checking: "<<curr<<" against: "<<temp<<std::endl;
            if(curr == temp)    ;
            {
                flag = true;
                std::cout<<"breaking"<<std::endl;
                
            }   
        }

So lets say the vector has elements {"Value1", "Value2", "Value3"}. Now for each iteration the if condition is satisfied even though there is no "Not Value" inside the vector. Below is the output using gdb:

checking: Value1 against: Not Value
245                         if(curr == temp)    ;
(gdb) p curr
$16 = "Value1"
(gdb) p temp
$17 = "Not Value"
(gdb) n
247                             flag = true;

As you can see the variables curr and temp hold different content and even then the if condition is satisfied. Both using cout and using gdb shows that the content of the variables are different. Is there some thing that i am doing wrong in this program?

PS: I have done this kind of usage many times and until today i never got any problem but for some reason this program doesn't work correctly. Maybe i am making some tiny mistake that i am unable to spot. So someone can help me spot it.

CodePudding user response:

Your if condition is empty. When you write

if(some_condition) ;
{
    //doing my thing
}

You simply have an if statement without a body. The body below is just a different scope unrelated to if.

To fix, simply remove ;

if(some_condition)
{
    //doing my thing
}
  • Related