Re: Function call evaluation order
- From: "Frederico Pissarra" <frederico@xxxxxxxxxxx>
- Date: Thu, 23 Mar 2006 16:49:35 -0300
"Cheng" <chengwuchew@xxxxxxxxxxx> escreveu na mensagem
news:u8X%23alhTGHA.4340@xxxxxxxxxxxxxxxxxxxxxxx
Hi folks,
I need help to explain the behavior with the code below. I would like to
chain up function call into a single line, while the order of the function
call is correct, I cannot be certain with order the expression within the
function call is evaluated.
Woud it be better, then, to write all the function call into seperate
lines?
With regards,
Cheng Wu
Code:
#include <stdio.h>
#include <string>
using namespace std;
void main()
{
char* data[] = {" zero ", " one ", " two ", " three "};
string s;
int i;
i = 0;
s.assign(data[i++]).append(data[i++]).append(data[i++]);
printf("%s\n", s.c_str());
i = 0;
s.assign(data[++i]).append(data[++i]).append(data[++i]);
printf("%s\n", s.c_str());
i = 0;
s.assign(data[i++]);
s.append(data[i++]);
s.append(data[i++]);
printf("%s\n", s.c_str());
}
Output:
zero zero zero
three three three
zero one two
It seems obvious to me that assign() will be performed before the first
append(), and this one before the second one. Obvious because member
selecion operator "." has the higher precedence and it's evaluated left to
right.
At the same time, in the first s.assign()... the routine uses post-increment
operators, so "i" will be incremented AFTER the expression is evaluated. The
same happens in the second s.assing().... but with pre-increment.
The last sentences are evaluated separately, so "s.assing(data[i++])" is the
same as "s.assign(data[i]); i++;".
Take a look at the precedence table in any good C book (or MSDN)... you'll
notice that . has the higher precedence... followed by ->, followed by [],
followed by funcion call "()"...
Hope it helped!
[]s
Fred
.
- Follow-Ups:
- Re: Function call evaluation order
- From: Carl Daniel [VC++ MVP]
- Re: Function call evaluation order
- References:
- Function call evaluation order
- From: Cheng
- Function call evaluation order
- Prev by Date: Re: C++ code audit/analysis tools?
- Next by Date: Re: Function call evaluation order
- Previous by thread: Re: Function call evaluation order
- Next by thread: Re: Function call evaluation order
- Index(es):