Skip to main content

Featured

functions in Python

Tutorial on Prefix and Postfix in C programming


The prefix and postfix notations in C++ are really simple for an expert but extremely difficult for novice to understand. In this tutorial, you can easily understand the working of increment and decrement operators in prefix and postfix notation.

Consider the following codes
Code 1
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int b,i=10;
b=i++ + ++i;
cout<<b;
getch();
}

OUTPUT will be 22.

Code 2
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i=10;
i=i++ + ++i;
cout<<i;
getch();
}

OUTPUT will be 23.

Wonder how? Do not wonder. I will explain how it works.

Explanation: Prefix notation is always given first priority over postfix notation to execute. Just see the priority setting for each operation and understand how it works:

Code 1
b=3(i++)4+2 (++i)1;

See the priority orders as 1, 2, 3 and 4. First prefix i increases and becomes 11. Secondly, + operator adds 11+11 and thirdly = operator assigns 22 to b and lastly postfix i increases to 12. So finally b=22 and i=12.

Code 2
i=3(i++)4+2 (++i)1;

See the priority orders as 1, 2, 3 and 4. First prefix i increases and becomes 11. Secondly, + operator adds 11+11 and thirdly = operator assigns 22 to i and lastly postfix i increases to 23. So finally i=23.

I hope you understood the working of prefix and postfix in the above examples. Share it if you liked this tutorial.

Comments

Popular Posts