MC logo
Increment Operators
[^] CSc 220 Home
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Standards] [Programming Environment] [Hello, World!] [Hello Again, World!] [Identifiers] [Constants] [Average of Three] [Basic Types] [Shortcut Operators] [Increment Operators] [C++ Strings]
#include <iostream>
using namespace std;

int main() 
        int fred = 14;
        int joe = 42;
        int alex = 0;

        alex = fred++;
        cout << "A: alex=" << alex << ", fred=" << fred << endl;

        alex = ++joe;
        cout << "B: alex=" << alex << ", joe=" << joe << endl;

        alex = --fred;
        cout << "C: alex=" << alex << ", fred=" << fred << endl;

        alex = joe--;
        cout << "D: alex=" << alex << ", joe=" << joe << endl;

        cout << "And now: " << alex++ + --fred * ++joe << endl;

++x: Returns the new value of x.

x++: Returns the old value of x.

It matters which only when the return value is used:
x++; and ++x; are the same.

Increment operators are similar to Java.
Things like x + ++x are not well-defined in C.
In the context of C, increments are better able to create bizarre programs.

An expression has a value. If it changes any of its variables, that is called a side effect.

x++ and ++x have the different values but the same side-effect. x+1 has the same value as ++x, but no side effect.