Nested function call and references

1
2
3
4
5
6
7
8
9
10
11
12
13
14
vector<int> decompose( string& number, bool& is_neg );
void print( const vector<int>& vec, const bool is_neg );

int main( )
{
    for( string num{}; cin >> num; ) {
	bool is_neg{};
	//vector<int> vec{ decompose( num, is_neg ) };
	//print( vec, is_neg );

	print( decompose( num, is_neg ), is_neg );
	cout << "\n";
    }
}

Nested function call:

-1234
= 1 thousand and 2 hundreds and 3 tens and 4 ones

1234
= 1 thousand and 2 hundreds and 3 tens and 4 ones

Separate function calls:

-1234
= minus 1 thousand and 2 hundreds and 3 tens and 4 ones

1234
= 1 thousand and 2 hundreds and 3 tens and 4 ones


Why does the nested function call cause is_neg to not be modified?
Last edited on
Why does the nested function call cause is_neg to not be modified?

It still modifies the is_neg, but the order is different.
print( decompose( num, is_neg ), is_neg );

The program will attempt to push the following parameters before calling print() :
1. is_neg.
2. The result of decompose( num, is_neg).

It is an assembly rule. The values are pushed in the reverse order.

That is why you need to do this if you want to see the value change :
void print( const vector<int>& vec, const bool &is_neg)
Oh, that makes sense thanks! :)
I just reversed the order of print so that is_neg is the first parameter and that seemed to fix it.
The order of evaluation of function arguments is unsequenced (until C++17).

From ISO/IEC 14882:2011 (C++11) ยง1.9.15, p.11
"Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced."
And
"If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined."

So in terms of standard C++, the behavior is undefined.
Topic archived. No new replies allowed.