Re: Function call evaluation order
- From: "Frederico Pissarra" <frederico@xxxxxxxxxxx>
- Date: Fri, 24 Mar 2006 14:26:33 -0300
"Carl Daniel [VC++ MVP]" <cpdaniel_remove_this_and_nospam@xxxxxxxxxxxxxxx>
escreveu na mensagem news:O1z0A71TGHA.4740@xxxxxxxxxxxxxxxxxxxxxxx
Here's an even better one:
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
template <class T>
T inc(T& i)
{
T t = i;
++i;
return t;
}
void f1()
{
char* data[] = { "one ", "two ", "three " };
int i = 0;
string s;
s.assign(data[i++]).append(data[i++]).append(data[i++]);
cout << s << endl;
}
void f2()
{
char* data[] = { "one ", "two ", "three " };
int i = 0;
string s;
s.assign(data[inc(i)]).append(data[inc(i)]).append(data[inc(i)]);
cout << s << endl;
}
void f3()
{
char* data[] = { "one ", "two ", "three " };
int i = 0;
string s;
s.assign(data[i++]);
s.append(data[i++]);
s.append(data[i++]);
cout << s << endl;
}
int main()
{
f1();
f2();
f3();
}
compiled with or without optimization, with VC8 or VC7.1 outputs
one one one
three two one
one two three
If precendence alone were enough, all three lines would be the same.
Undefined behavior in action! Only f3 has well-defined behavior - it must
produce "one two three " according to the C++ standard. f2 has partially
defined behavior as the only valid outputs from it consist of the strings
"one ", "two " and "three " once each in some undefined order. f1
has.completely undefined behavior since i is modified twice between
sequence points.
-cd
And think about the standard strcpy() function... It is implemented in C
like this:
char *strcpy(char *dest, char *src)
{
char *sTemp = *dest;
while (*dest++ = *src++);
return dest;
}
if the post increments are supposed to be evaluated sequentially the routine
will never work!
[]s
Fred
.
- Follow-Ups:
- Re: Function call evaluation order
- From: Tom Widmer [VC++ MVP]
- Re: Function call evaluation order
- References:
- Function call evaluation order
- From: Cheng
- Re: Function call evaluation order
- From: Frederico Pissarra
- Re: Function call evaluation order
- From: Carl Daniel [VC++ MVP]
- Re: Function call evaluation order
- From: Frederico Pissarra
- Re: Function call evaluation order
- From: Carl Daniel [VC++ MVP]
- Re: Function call evaluation order
- From: Frederico Pissarra
- Re: Function call evaluation order
- From: Carl Daniel [VC++ MVP]
- Re: Function call evaluation order
- From: Carl Daniel [VC++ MVP]
- Function call evaluation order
- Prev by Date: Re: Function call evaluation order
- Next by Date: Re: not a warning?
- Previous by thread: Re: Function call evaluation order
- Next by thread: Re: Function call evaluation order
- Index(es):
Relevant Pages
|