Skip to content

Instantly share code, notes, and snippets.

@moshekaplan
Created September 13, 2012 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moshekaplan/3711576 to your computer and use it in GitHub Desktop.
Save moshekaplan/3711576 to your computer and use it in GitHub Desktop.
Pre and Post increment
#include <iostream>
using namespace std;
int preincrement(int & x){
// Add one to x, and return the new value for x.
x = x+1;
return x;
}
int postincrement(int & x){
// Copy x to a temporary variable, add one to x, and return the original value of x that's stored in temp.
int temp = x;
x = x+1;
return temp;
}
int main(){
// Initialize x to a silly value, like 42.
int x = 42;
// Well, x hasn't changed yet. Prints 42.
cout << x << endl;
// This will increment x and then return x: Prints 43.
cout << preincrement(x) << endl;
// Prints 43.
cout << x << endl;
// This will make a copy of x, increment x, and return x: Prints 43.
cout << postincrement(x) << endl;
// Prints 44
cout << x << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment