My question that needs an answer is this:
Can the C++ compilers catch the mistake of using an "=" instead of the comparison operator "==".
Show code how you can test this using an if statement in C++, write a small program to demonstrate it.
If the compiler does not catch the mistake how would one go about ensuring they are using the correct syntax for the comparison operator?
Thank you
#include <iostream>
using namespace std;
int main()
{
int x = 20;
int y = 18;
if (x = y) //TYPO
{
cout << "x is equal to y";
}
else
cout << "x is not equal to y";
cout <<x;
cout << y;
return 0;
}
Running a modern compiler at the highest warning level will cause it to issue a warning when an assignment is used in a conditional statement or a note that the statement does nothing when an equality test is used instead of an assignment outside of a conditional. This is one issue that is essentially fixable -- if you use the higher warning levels.
So programmers must be careful while using == operator.
Get Answers For Free
Most questions answered within 1 hours.