Funny C++
-
Who can explain : char *m="az"; cout << m << endl; i=0; cout << m[i++] << m[i++] << endl ; i=0; ((cout.operator<<(m[i++])).operator <<( m[i++])).operator <<(endl) ; Gives (Visual C++) 6.0 : az za za Thanks .
Using more than one
++
or--
operator on anything but a line by themselves is always risky. Looking at the statement:cout << m[i++] << m[i++] << endl;
the
i++
statement gets executed first, and that value (1) is used with the[]
operator.
"The pointy end goes in the other man." - Antonio Banderas (Zorro, 1998)
-
Who can explain : char *m="az"; cout << m << endl; i=0; cout << m[i++] << m[i++] << endl ; i=0; ((cout.operator<<(m[i++])).operator <<( m[i++])).operator <<(endl) ; Gives (Visual C++) 6.0 : az za za Thanks .
-
Using more than one
++
or--
operator on anything but a line by themselves is always risky. Looking at the statement:cout << m[i++] << m[i++] << endl;
the
i++
statement gets executed first, and that value (1) is used with the[]
operator.
"The pointy end goes in the other man." - Antonio Banderas (Zorro, 1998)
-
Using more than one
++
or--
operator on anything but a line by themselves is always risky. Looking at the statement:cout << m[i++] << m[i++] << endl;
the
i++
statement gets executed first, and that value (1) is used with the[]
operator.
"The pointy end goes in the other man." - Antonio Banderas (Zorro, 1998)
Um, no. The problem here is the undefined behavior of the multiple ++ operations which does get you into some problems. int i = 0; cout << m[i++] << endl; This code would fetch the 0'th value. The ++ and -- operators are not risky when you know how to use them. They have well defined behaviors and undefined behaviors. Tim Smith I'm going to patent thought. I have yet to see any prior art.
-
sorry but the value of i used by the [] operator will be 0 ... I think you're confused whith ++i ...
cout << i++ << i++ << endl;
Stepping into the code for
ostream& ostream::operator<<(int n)
revealed thatn
had a value of 1 the first time, and a value of 0 the second time. Had the pre-increment operator been used instead, a subscript-out-of-range error would have been realized since the value ofn
would have been 2 the first time through. Separating thei++
operations into two statements solves all the problems.
"The pointy end goes in the other man." - Antonio Banderas (Zorro, 1998)