In this example, we implement the pre- and post-increment operators as functions to better understand their semantics. The code is in C++.
#include <cstdlib>
#include <iostream>
using namespace std;
int postIncrement(int & c)
{
int x = c;
c = c + 1;
return x;
}
int preIncrement(int & c)
{
c = c + 1;
return c;
}
void print(int c, int b)
{
cerr << "c=" << c << "b=" << b << endl;
}
int main()
{
{
int c = 1;
int b = (c++) + 2;
print(c, b);
b = ++c + 2;
print(c, b);
b = -c++;
print(c, b);
b = -++c;
print(c, b);
}
printf("\n");
{
int c = 1;
int b = postIncrement(c) + 2;
print(c, b);
b = preIncrement(c) + 2;
print(c, b);
b = -postIncrement(c);
print(c, b);
b = -preIncrement(c);
print(c, b);
}
return EXIT_SUCCESS;
}