Increment Operator Behavior When Passed as Function Parameters in C++
In C++, an increment operator is used to increment the value of the variable by 1. The symbol ++ is used to represent the increment operator. There are two types of increment operators:
- Pre-Increment Operator: This form of increment operator increases the value of the variable by 1 before assigning it to the variable.
- Post-Increment Operator: This form of increment operator increases the value of the variable by 1 after assigning the variable.
5 5 5
One must be wondering the output can be 3, 4, 5, or 5, 4, 3, or any combination. But the output is 5 5 5. But it is the nature or behavior of the increment operator. The source location or memory where the value of variable i is stored is constant and every increment operator is increasing value there only. It will be more clear after one more example. Let’s have a look at one more program.
Below is the C++ program to implement the pre and post-increment operators.
7 6 8
Here the output is also different. Strange, isn’t it? C++ Standard doesn’t tell about the order of evaluation of parameters. So it can be evaluated based on the compiler behavior.
You must be wondering the output should be 6 7 8 according to the concept explained in the previous example.
If one is wondering according to the post-increment concept, the value is used first and then incremented. So the value in 1st argument should be 5. But the answer is no. Recall the principle of memory and source location, and then apply post and pre-increment concepts. Try to apply both concepts on test cases like fun(++i, i++, ++i) and try to predict output for various test cases, and then it would surely make sense to you but the order may vary in occurrence according to C++ standard.