Monday, November 23, 2020

Linux: Comma separated arguments in an If Statement

 What happens when you write code like this:

    if ((x,y) == true) {

Is it even a legal condition to put in? If yes, why would you use it?

We have an example you could try out:

bash-4.1$ cat test.cc 
#include <iostream>
using namespace std;
int main() {
    int x = 1, y =0;
    if ((x,y) == true) {
        cout << “X TRUE PATH" << endl;
    } else {
        cout << “Y FALSE PATH" << endl;
    }
}

It turns out when you do this GCC will pick the last argument and run a comparison against it. So the answer is:

bash-4.1$ ./test 
Y FALSE PATH