Unary Operators

C includes a class of operators that act open a single operand to produce a new value. Such operators are known as unary operators. Unary operators usually precede their single operands, through some unary operators are written after their operands.

The most common unary operation is unary minus, where a minus sign precedes a numerical constant, a variable, an expression. For example

-220     -z     -(a+b)

C provides two unusual unary operations for incrementing and decrementing variable. The increment operator ++ adds 1 to its operand, while the decrement operator – subtracts 1. The unusual aspect is that ++ and - - may be used either as prefix operators (before the variable, as in ++x), or postfix (after the variable as x++). In both cases, the effect is to increment x. But the expression ++x increments x before its value is used, while x++ increments x after its value has been used. This means that in a context where the value is being used, ++x and x++ are different. If x is 5, then

y = x++;

sets y to 5, but

y = ++x;

sets y to 6.


In both cases, x becomes 6. The increment and decrement operators can only be applied to variables; an expression like (x+y) ++is illegal. But in a context where no value is wanted, just the incrementing effect, prefix and postfix are the same.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext