Re: Why does this work?
From: Anthony Borla (ajborla_at_bigpond.com)
Date: 03/26/05
- Next message: Anthony Borla: "Re: 3-day novice, How do I calculate age in days? [C++]"
- Previous message: John Peters: "Why does this work?"
- In reply to: John Peters: "Why does this work?"
- Next in thread: James Dennett: "Re: Why does this work?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 26 Mar 2005 22:02:42 GMT
"John Peters" <john@jpeters.net> wrote in message
news:d6ydne5YbfWoT9jfRVn-tg@comcast.com...
>
> I'm curious why the cout in the function prints before
> the cout in main.
>
> Thus:
>
> "Calling sum 3 + 4
> The sum is :7"
>
> //Code:
>
> int sum(int x, int y);
>
> #pragma argsused
> int main(int argc, char* argv[])
> {
>
> cout<< "The sum is :" << sum(3,4);
> cin.get();
> return 0;
> }
>
> int sum(int x, int y)
> {
> cout << "Calling sum " <<x <<" + " << y <<"\n";
> return x+y;
> }
>
The following line:
cout << "The sum is :" << sum(3,4);
sees the 'sum' function called [supplied with the arguments, 3, and 4], and
the code within its body executed, and a result returned - prior to - the
'cout' statement [term used loosely] is, iteself, executed.
In effect, the function call is replaced with it's returned value:
cout << "The sum is :" << 7;
However, since the body of the function also contains a 'cout' statement,
*it* is executed as part of function execution, thus its output appears
prior to that of the original.
This is an example of what is termed a 'side effect': a function's execution
not only sees a return value computed, but, as a consequence of executing,
impacts on other parts of the program, sometimes in unhelpful ways.
To avoid such possibilities the remedy is to code in a way that avoids, or
at least minimises, such 'side effects'. One way to do this is to design
functions so that they only perform steps that contribute to a single task.
In the current case, the following approach could have been used:
#include <iostream>
int sum(int x, int y);
int main(int argc, char* argv[])
{
int x = 3, y = 4;
cout << "Calling sum " << x << " + " << y << endl;
cout<< "The sum is :" << sum(x, y);
cin.get();
return 0;
}
int sum(int x, int y)
{
return x+y;
}
As you should have noticed, the 'sum' function is now side effect-free, and
can be used in situations not involving console output. This makes it a more
useful function that it was previously.
I hope this helps.
Anthony Borla
- Next message: Anthony Borla: "Re: 3-day novice, How do I calculate age in days? [C++]"
- Previous message: John Peters: "Why does this work?"
- In reply to: John Peters: "Why does this work?"
- Next in thread: James Dennett: "Re: Why does this work?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|