In this article iam going to talk about C++ Short Hand If Else (Ternary Operator) , also we can call it ternary operator, because it consists of three operands. and it can be used to replace multiple lines of code with a single line.

Also you can check more articles on c++ programming language

1: C++ Introduction & Program Structure
2: C++ Variables And Data Types
3: C++ Getting User Input
4: C++ If Else Statement

Expression1 ? Expression2 : Expression3;

So above is the syntax for ternary operator, we have three expressions, you can see the using of colon (:) and question mark (?) in this syntax. it means that we are checking if the Expression1 is true, we are going to execute the statement after that question mark that is Expression2, and in the else case if the Expression1 is false we are going to execute the code or statement after the colon that is Expression3 . the (?) is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form.

#include<iostream>

using namespace std;

int main() {

   
	int number = 10;


	if (number >= 10) {
	cout << "Number is greater than 10 " << endl;
	}

	else
	{
	cout << "number is less than 10" << endl;
	}

	


	
	return 0;

}

No you can replace that with the shorthand if else like this .

#include<iostream>

using namespace std;

int main() {
	 
	int number = 10;

	number >= 10 ? cout << "Number is greater than 10" << endl : cout << "Number is    greater than 10" << endl;
	


	
	return 0;

}

So in the code we have used ternary operator and we are checking our conditions.

After run this will be the result

Number is greater than 10
Press any key to continue . . .

OK now let’s just create another example, this time we are going to check the condition according to the user input.

#include<iostream>

using namespace std;

int main() {
	 

	int a;
	int b;

	int c = 20;

	int sum;



	cout << "Please enter first number : " << endl;
	cin >> a;

	cout << "Please enter second number : " << endl;
	cin >> b;

	sum = a + b;

	sum >= c ? cout << " Sum is greater than c value " << endl : cout << "Sum is less than c value" << endl;


	
	return 0;

}

In the above code first we are getting two numbers from the user, after that we sum the numbers and check that value with predefined value of c that we have. after run this will be the result.

Please enter first number :
5
Please enter second number :
7
Sum is less than c value
Press any key to continue . . .

#c++ #cplusplus #web-development

Short Hand If Else (Ternary Operator ) In C++
1.40 GEEK