#include <iostream>
#include <string>
#define S string::
usingnamespace 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>
usingnamespace std;
int five(int &x)
{
x*=2;
return 5;
}
int main()
{
int x=2;
cout<<five(x)<<endl<<x<<endl;
cout<<x<<endl;
}