TechGeeks

Conditional or Ternary Operators

The operators are used for decision making in C programming are known as conditional operators, i.e, executes different statements according to test condition whether it is either true or false.

Syntax :
conditional_expression?expression1:expression2 

If the test condition is true (that is, if its value is non-zero), expression1 is returned and if false expression2 is returned.

Let's understand this with the help of a few examples:

int a, b ;

scanf ( ā€œ%dā€, &a );

b = ( a> 5 ? 3 : 4 );

This statement will store 3 in b if a is greater than 5, otherwise it will store 4 in b.
The equivalent if statement will be,

if ( a > 5 )

{

b = 3 ;

}

else

{

b = 4 ;

}

Miscellaneous Operators

There are a few other operators supported by c language.

Operator : ( sizeof() )

Description: It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.

Example: sizeof(a), where a is an integer, will return 4.

Operator : ( & )

Description: Returns the address of a variable.

Example: &a will give us the actual address of the variable.

Operator : ( * )

Description: Pointer to a variable.

Example: *a; will be a pointer to a variable.

Increment and Decrement Operators

In C language, ( ++) and ( -- ) are called increment and decrement operators respectively. Both of these operators are called as unary operators, i.e, used on single operand. ++ adds 1 to the operand whereas -- subtracts 1 from operand respectively.

For example:

Let a=1 and b=2

a++; /*a becomes 2 */

a--; /*a becomes 1 */

++a; /*a becomes 2 */

--a; /*a becomes 1 */

When i++ is used as prefix(like: ++variable), ++variable will increment the value of variable and then return it but, if ++ is used as postfix(like: variable++), the operator will return the value of operand first and only then it will increment it.

<<Back Next >>