Can (a==1)&&(a==2)&&(a==3) evaluate to true? (and can it be useful?)

前端 未结 8 1510
北荒
北荒 2021-01-15 11:34

Inspired by another question regarding java-script language. Can the expression

 (a==1)&&(a==2)&&(a==3)

evaluate to true i

8条回答
  •  醉话见心
    2021-01-15 12:03

    As it was noticed before, this trick could be performed with volatile. This is more honest approach compared to operator changing. Just let us use two threads:

    volatile int a;
    
    void changingValue(){
        std::srand(unsigned(std::time(0)));
        while (true) {
            a = (rand() % 3 + 1);
        }
    }
    
    void checkingValue(){
        while (true) {
            if (a == 1 && a == 2 && a == 3) {
                std::cout << "Good choice!" << std::endl;
            }
        }
    }
    
    int main() {
        std::thread changeValue = std::thread(changingValue);
        changeValue.detach();
        std::thread checkValue = std::thread(checkingValue);
        checkValue.detach();
        while (true){
            continue;
        }
    }
    

    Moreover, this code in my case is working well with no volatile declaration. As far as I understand, it should depend on compiler and processor. Maybe someone could correct it, if I'm wrong.

提交回复
热议问题