0

Hi all,

The topic is my question. I’ll explain it more. Just look at the following C++ code segment,

if(number_1 == number_2);
	{
		std::cout << number_1 << " == " << number_2 << std::endl;
	}

Note that, I have put a semicolon just after the right parentheses. It’s not a syntax error, because at the compile time it not gives an error. So, it should be a logic error. I found that semicolon causes the body of the “if” statement to be empty, from a book. So, there can’t be a output like “5 == 5”, if my input are 5 and 5 on the following code.

#include <iostream>	
//using namespace std;

int main()
{
	int number_1;	
	int number_2;	

	std::cout << "Enter two numbers:\t";
	std::cin >> number_1 >> number_2 ;

	if(number_1 == number_2);
	{
		std::cout << number_1 << " == " << number_2 << std::endl;
	}

	if(number_1 != number_2)
	{
		std::cout << number_1 << " != " << number_2 << std::endl;
	}
	return 0;
}

So where I’m going wrong, my code or my scrap on that book explanation.

2
Contributors
2
Replies
4
Views
9 Years
Discussion Span
Last Post by eranga262154
0

The semicolon tells the 'if statement' to do nothing when it is placed directly after it. In other words: if the statement is true do: ';' (nothing)
When the program passes that point it comes to:

{
     std::cout << number_1 << " == " << number_2 << std::endl;
 }

This part will now always be executed, because there is no longer a condition attached to it :)

So just remove the semicolon and you're back in business

Edited by Nick Evan: n/a

0

That mean just print a line, I've test it using my inputs as 4 and 5. Still it give the line 4 == 5. That is 100% correct and I got the point.

Now I know why I'm confusing on this, because at the beginning I used the same inputs.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.