Tuesday, October 18, 2011

The Conditional Operator

The conditional operator ?: allows writing more simple conditional expressions in  which you can select one of two statements according to a logical condition.

Syntax
(condition)?(condition_true_statement):(condition_false_statement)

Example:
int i=3,j;
(i==3)?(j=5):(j=3);
//j will become equal to 5
Also, the conditional operator can be used for assigning a value to a variable according to a condtion.

Syntax
variable = (condition)?(condition_true_value):(condition_false_value)

Example:
int i=3,j;
j=(i==3)?(5):(3);
//j will become equal to 5
The conditional operator is mostly used in the C language, but is accepted also in C++, C# and Java (still, some people consider it not fit for object-oriented programming).

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger