Question about functions

I've got a quick question about functions. I'm working on passing two variables through a function, which is working, I'm just noticing something..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#define S string::

using namespace std;


S size_type analyzeString(const string &s, char c, S size_type &occurs)
{
	S size_type wordCount = 0;
	occurs = 0;
	for(S size_type i = 0; i != s.size(); ++i)
	{
		if (isspace(s[i]) || s[i] == '.')
		{
			wordCount++;
		}
		if (s[i] == c)
		{
			++occurs;
		}
	}

	return wordCount;
}

int main()
{
	S size_type ctr = 0;

        //Will return 5 0
	cout << analyzeString("This is a test string.", 'i',ctr) << endl << ctr << endl;

	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
...
int main()
{
    S size_type ctr = 0;
    auto index = analyzeString("This is a test string.", 'i', ctr);

    //Would return 5 3
    cout << index << endl << ctr << endl;

    return 0;
}


Why is there a difference between the code in the first int main(){...} and the second that would make ctr equal 0 instead of it's intended value of 3?
The order the arguments of function calls (or operators) are evaluated is not specified in C++ standards. So your compiler sees ctr, it stores that value for the output, then evaluates analyzeString, where a new ctr is calculated. Try
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int five(int &x)
{
 x*=2;
 return 5;
}

int main()
{
 int x=2;
 cout<<five(x)<<endl<<x<<endl;
 cout<<x<<endl;
}

I get
1
2
3
5
2
4


For more detailed explanation see http://stackoverflow.com/questions/1504752/c-output-evaluation-order-with-embedded-function-calls
Last edited on
Ah! Thank you so much ats15, it was definitely confusing me.
Topic archived. No new replies allowed.