Cpp - Unary Arithmetic Operators

Introduction

There are four unary arithmetic operators: the sign operators + and -, the increment operator ++, and the decrement operator --.

Operator Significance
+ - Unary sign operators
++ Increment operator
-- Decrement operator

Effects of prefix and postfix notation

#include <iostream> 
using namespace std; 
int main() 
{ 
    int i(2), j(8); 

    cout << i++ << endl;       // Output:  2 
    cout << i   << endl;       // Output:  3 
    cout << j-- << endl;       // Output:  8 
    cout << --j << endl;       // Output:  6 

    return 0; 
} 

Sign Operators

The sign operator - returns the value of the operand but inverts the sign.

int n = -5;   
cout << -n;    // Output: 5 

The sign operator + performs no useful operation, simply returning the value of its operand.

Increment / Decrement Operators

The increment operator ++ modifies the operand by adding 1 to its value.

Given that i is a variable, both i++ (postfix notation ) and ++i (prefix notation ) raise the value of i by 1.

In both cases the operation i=i+1 is performed.

Prefix ++ and postfix ++ are two different operators.

++i returns the value of i incremented by 1, whereas i++ retains the original value of i.

Expression Meaning
++ii is incremented first and the new value of i is then applied,
i++the original value of i is applied before i is incremented.

The decrement operator -- modifies the operand by reducing the value of the operand by 1.

Prefix or postfix notation can be used with --.

Precedence

Precedence of arithmetic operators

Precedence
Operator
Grouping
High



++ -- (postfix)
++ -- (prefix)
+ - (sign)
* / %
left to right
right to left

left to right
Low

+ (addition)
- (subtraction)
left to right

Operator precedence determines the order of evaluation.

++ has the highest precedence and / has a higher precedence than -.

Consider the following code

float val(5.0);  
cout << val++ - 7.0/2.0; 

The example is evaluated as follows:

(val++) - (7.0/2.0). 

The result is 1.5, as val is incremented later.

If two operators have equal precedence, the expression will be evaluated as shown in column three of the table.

3 * 5 % 2 is equivalent to (3 * 5) % 2

Related Topic