Created
September 13, 2012 03:07
-
-
Save moshekaplan/3711576 to your computer and use it in GitHub Desktop.
Pre and Post increment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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