Nasty autoincrement! - top of Musings page

By: Nicholas Duchon.


Try explaining these results to your students, or yourself, or anyone else who happens to be willing to listen:

C++ Code

#include < iostream>
#include < iomanip>

using namespace std;

int main() {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int g = 0;
int h = 0;
cout << setw (5) << "i"
<< setw (5) << "a"
<< setw (5) << "b"
<< setw (5) << "c"
<< setw (5) << "d"
<< setw (5) << "e"
<< setw (5) << "f"
<< setw (5) << "g"
<< setw (8) << "h"
<< endl;
for (int i = 0; i < 10; i++) {
cout << setw (5) << i
<< setw (5) << a
<< setw (5) << b
<< setw (5) << c
<< setw (5) << d
<< setw (5) << e
<< setw (5) << f
<< setw (5) << g
<< setw (8) << h
<< endl;
a += 1;
b++;
c = c++;
d = 0 + d++;
e = 1 + e++;
f += f++;
g = g + g++;
h += h++ + h++;
} // end for
return 0;
} // end main

Output - C++, Cygwin version integrated in jGrasp


i a b c d e f g h
0 0 0 0 0 0 0 0 0
1 1 1 0 0 2 1 1 2
2 2 2 0 0 4 3 3 8
3 3 3 0 0 6 7 7 26
4 4 4 0 0 8 15 15 80
5 5 5 0 0 10 31 31 242
6 6 6 0 0 12 63 63 728
7 7 7 0 0 14 127 127 2186
8 8 8 0 0 16 255 255 6560
9 9 9 0 0 18 511 511 19682

g++ on nova, g++ (GCC) 3.2.3


i a b c d e f g h
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9

Using MS Visual C++ Express 2005


i a b c d e f g h
0 0 0 0 0 0 0 0 0
1 1 1 1 1 2 1 1 2
2 2 2 2 2 4 3 3 8
3 3 3 3 3 6 7 7 26
4 4 4 4 4 8 15 15 80
5 5 5 5 5 10 31 31 242
6 6 6 6 6 12 63 63 728
7 7 7 7 7 14 127 127 2186
8 8 8 8 8 16 255 255 6560
9 9 9 9 9 18 511 511 19682

Java 6.0


public class IncrementTest {

public static void main (String args []) {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int g = 0;
int h = 0;
System.out.printf ("%5s%5s%5s%5s%5s%5s%5s%5s\n", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
for (int i = 0; i < 10; i++) {
System.out.printf ("%5d%5d%5d%5d%5d%5d%5d%5d\n", a, b, c, d, e, f, g, h);
a += 1;
b++;
c = c++;
d = 0 + d++;
e = 1 + e++;
f += f++;
g = g + g++;
h += h++ + h++;
} // end count
} // end main

} // end class IncrementTest

Java Output


a b c d e f g h
0 0 0 0 0 0 0 0
1 1 0 0 1 0 0 1
2 2 0 0 2 0 0 4
3 3 0 0 3 0 0 13
4 4 0 0 4 0 0 40
5 5 0 0 5 0 0 121
6 6 0 0 6 0 0 364
7 7 0 0 7 0 0 1093
8 8 0 0 8 0 0 3280
9 9 0 0 9 0 0 9841

Nick.