0

Out of the two versions (below) of condition check which version is better? and Why?

Version 1:

#include<iostream>
using namespace std;
int main()
{
int x;
cin >> x;
if (x == 1) // version 1
    { cout << "Hello world!" << endl;
  }

return 0 ;
}

Version 2:

#include<iostream>
using namespace std;
int main()
{
int x;
cin >> x;
if (1 == x) // version 2
    { cout << "Hello world!" << endl;
  }

return 0 ;
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53
Faraz Alam
  • 23
  • 1

1 Answers1

1

These are the same, the only advantage I can see relates do error detection.

Lets say you mistakenly write 1 = x, you will have a compilation error.

If you write x = 1 then the condition will evaluate to true, x will be assigned the value 1, the program will compile fine but it will not have the expected ouptput and it might be hard to detect this kind of error, though you have compiler warnings that you can turn on for this kind of situation.

anastaciu
  • 23,467
  • 7
  • 28
  • 53