Tuesday 12 February 2013

Ternary Operators in C Programming Language



C offers a shorthand way of writing the commonly used if - else statement.

if ( condition )
{
statements if condition is true
}
else
{
statements if conditions is false
}

An example of this is shown below:

larger_of_the_two = (x>y)?x:y;

The manner in which the above statement works is quite straightforward. The expression within the () is tested. If x is greater than y, larger_of_the_two will be assigned the value x. Otherwise, it will take on the value y.

This shorthand can reduce code in many situations.

The general form of an expression that uses the ternary operator(right-had side of the above statement) is:

(test-expression) ? T-expression : F - expression;

The expression contains 3 parts and thus the term ternary.

Compound Assignment Operators in C Language Tutorial

Apart from the standard assignment operator (=), C offers compound asignment operators which simplify the following statements.

For example:

total=total+ some_value;

can be written as:

total+=some_value;

Another example is:

total-=some_other-value;

The general form of this compound assignment is:

left-value op=right-expression;

where op can be either +(add), - (subtract, *(multiply), /(divide) and %(modulo).

The above general form translates to:

left-value = left - value op right-expression;

The compound assignment is usefull, especially when long variable name are used, as in:

a_vary_long_identifier=a_very_long-identifier + 2;

which can be written as:

a_very_long_identifier+ = 2;

The notation saves much typing effort without obscuring the meaning.

0 comments:

Post a Comment

Powered by Blogger.