Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefix and postfix operators necessity

Tags:

c

What is the necessity of both prefix and postfix increment operators? Is not one enough?

To the point, there exists like a similar while/do-while necessity problem, yet, there is not so much confusion (in understanding and usage) in having them both. But with having both prefix and postfix (like priority of these operators, their association, usage, working). And do anyone been through a situation where you said "Hey, I am going to use postfix increment. Its useful here."

like image 999
Karthik Avatar asked Jul 02 '13 16:07

Karthik


People also ask

What are the advantages of prefix notation?

Less repetitive. Another reason prefix notation can be nice is that it can make long expressions less repetitive. With prefix notation, if we plan to use the same operator on many operands, we do not have to repeat the operator between them.

Is it better to use postfix or prefix?

Conversion of Prefix expression directly to Postfix without going through the process of converting them first to Infix and then to Postfix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression).

What is the use of postfix and infix operation?

Infix expression is an expression in which the operator is in the middle of operands, like operand operator operand. Postfix expression is an expression in which the operator is after operands, like operand operator. Postfix expressions are easily computed by the system but are not human readable.

What is postfix and prefix operators?

Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased). Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable.


1 Answers

POSTFIX and PREFIX are not the same. POSTFIX increments/decrements only after the current statement/instruction is over. Whereas PREFIX increments/decrements and then executes the current step. Example, To run a loop n times,

while(n--)
{ }

works perfectly. But,

while(--n)
{
}

will run only n-1 times

Or for example:

x = n--; different then x = --n; (in second form value of x and n will be same). Off-course we can do same thing with binary operator - in multiple steps.

Point is suppose if there is only post -- then we have to write x = --n in two steps.

There can be other better reasons, But this is one I suppose a benefit to keep both prefix and postfix operator.

like image 142
Aswin Murugesh Avatar answered Nov 10 '22 07:11

Aswin Murugesh