recent posts

What is difference between postfix a++ and prefix ++a?



Hi, I'm Golam Rabbani. Today I will discuss about postfix and prefix operator.
Greetings! How are you all? Hope everyone is well.
#Topic 1: a++ is called post increment and will return a then increment a by 1
Equivalent to a++? Answer: a = a+1.

If a = 5;
print a++; //result = 5
print a; //result = 6

Program:
#include<stdio.h>
int main(){
    int a=5;
    printf("%d\n",a++);
    printf("%d\n",a);
    return 0;
}
#Topic 2: ++a is called pre increment and will increment a by 1
Equivalent to ++a? Answer: a = a+1. But this is different. What’s different?
If a = 5;
print ++a; //result = 6
Program:
#include<stdio.h>
int main(){
    int a=5;
    printf("%d\n",++a);
    printf("%d\n",a++);
    return 0;
}
Test your knowledge.
Question 1: pre increment and post increment in c program?
#include<stdio.h>
int main(){
    int a=5;
    printf("%d,%d,%d,%d,%d,%d,%d\n",a++,++a,a++,++a,a++,a++,++a);
    printf("%d",a);
}
Output:
a=5.
Remember ++a always view total result. This program continue 7 time increment. So, ++a always view a=5+7; a=12.
This case.
N = Not calculate. I mean a=12.
F = Count start > Right to left. When get first a++.

S.L
7
6
5
4
3
2
1
Count
6
5
4
3
2
1
Calculation
F
a=5+6
N
F
a=5+4
N
F
a=5+2
F
a=5+1
N
Operator
a++
++a
a++
++a
a++
a++
++a
Result
11
12
9
12
7
6
12

Compiler Result:


 Thank you everyone.
What is difference between postfix a++ and prefix ++a? What is difference between postfix a++ and prefix ++a? Reviewed by Golam Rabbani on November 23, 2018 Rating: 5

No comments:

top navigation

Powered by Blogger.