postfix and prefix : for beginners

postfix and prefix is the use of increment and decrement operators (++, –).

in c++ either before the variable or after the variable. To use the parameters, numeric variables of type int, float or double must be used.

and the process of increment before the variable is called Prefix, and the increment after the variable is called postfix, and there are many Of the postfix and prefix operations in C++.

some of them are becoming increasingly difficult to explain and implement, but we will only mention the most used in these two features.

 

1. Prefix

This feature is based on performing arithmetic and logic before the result appears on the console screen to display the new value in the playback screen, as it increases the variable at an earlier time before displaying the variable on the screen.

#include<iostream>
using namespace std;

int main() {
    fraction tot;
    tot.output();


    int a = 5;
    --a;
    cout << a << endl;


    return 0;
}

 

2.Postfix

This feature is based on performing the calculation and logic after the result of the variable appears on the console screen and the screen is closed, whether it increases or decreases, but as we said we cannot see the result after closing the console.

#include<iostream>
using namespace std;

int main() {
    fraction tot;
    tot.output();


    int a = 5;
    a--;
    cout << a << endl;


    return 0;
}

 

3. When do we use postfix and prefix?

As we said earlier, we have explained and simplified the idea as simple as possible. The purposes of using one of the two methods are many. However, dealing with the prefix is ​​very useful in programming graphics, especially when previewing the operation and recall, and is very useful when dealing with databases on the server page, in web pages, and we can say The two properties are available in most programming languages.

 

4. Example

Please, to understand the difference between postfix and prefix well, copy the following code into your code editor.

 

#include<iostream>
using namespace std;

int main() {

    int a = 5;
    --a;
    cout <<"This method is prefix : "<< a << endl;

    a--;
    cout << "This method is postfix : " << a << endl;

    int a = 5;
    ++a;
    cout << "This method is prefix : " << a << endl;

    a++;
    cout << "This method is postfix : " << a << endl;

    return 0;
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *