Question

I'm trying to design a construct that can check for errors in input, so I wrote two boolean functions in a test program whose parameters are string references. I was hoping my if statement would evaluate the first function- changing part of word, then evaluate the second function- changing word again, and finally evaluate the && to see whether print. My code won't run, however, and the error says that no operand matches the << operator for cout, when I'm trying to output the code. My code is can explain better than I. Could someone please explain why this won't work? I'm using Visual Studio 2012.

#include <iostream>
using namespace std;

bool changeString1(string &word){
    word[0]='a';
    return word[1]=='b';
}

bool changeString2(string &word){
    word[2]='c';
    return word[3]=='d';
}

int main(){
    cout << "hello" << endl;

    string word("cbad");
    if(changeString1(word) && changeString2(word)){
        cout << word << endl;
    }
    system("Pause");
    return 0;
}
Was it helpful?

Solution

Your problem is probably that you haven't got #include <string> in the beginning of your code.

The order of evaulation of && and || expressions is strictly "left to right", and guaranteed to "short circuit" when the expression is determined by the left operand.

When using other operators, it is undefined, so for example if (changeString1(word) + changeString2(word)), the compiler would be allowed to call changeString2 before changeString1.

In other words, when there is an && (and) in the expression, if the first condition is false, the second expression is not evaluated, and if the first expression is true, the second is evaluated. Since both are indeed true in this case, both are evaluated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top