+ 5
Error in C++ tutorial ??
In the " default values for parameters " of the C++ tutorial, the exemple declares two parameters ( a,b ) and then in the second section of the exemple, parameters ( x,y ) are declared with new ( different values ). Then, it seems that the value declared for b is recycled ( passed ? ) to y ... but without any code asigning b's value to y. Other users seem to be confused too ... Any super-user can take me by the hand ?
6 Answers
+ 1
I don't know what you mean (for me the code looks correct), but i will try to explain what happens.
we enter main function
int x is created and set to 24
int y is created and set to 36
now we call function sum:
x is passed to a (so a is now 24)
y is passed to b (so b is now 36)
int result is created from a and b (result is now 60)
result is returned
int result is now created and set to value function returned (60) (at the moment of return variables created in function stops existing)
(note that there is no coleration between "sum's result" and "main's result"; they are two different vars, cause they are both created elsewhere)
now we call sum again
x is passed to a (so a is now 24)
but there is nothing to pass to b, so b takes it's "default" value of 42 (so b is now 42)
result is now 24 + 42
I hope it will help you somehow.
+ 4
Ok so basically once you declare your function as :
int sum ( int a, int b );
and call it later in your code, the ( compiler ?? ) expects to see, or just expects 2 integers ( arguments ? ) assigned to that function ??? and will use them as values for that function. If no value is declared for a or b, it will resort to the default value if one has been declared, for arguments ( a&b ) or (1&2) or ( black&white ) ? Do I seem to get it .... Actually I do get it, it's just the b being substituted by y that messed with my brain ... Ok thanks man !
+ 3
I'm a little fuzzy on what you're detecting, because to me it looks okay (but I've seen it before).
One guess...scope (local vs global). The function doesn'tâ know anything about 'x' and 'y' (well...it would if it referred to the globals but it doesn't do that: it only uses 'a' and 'b', which are local to the function). You could pass in an integer named 'toast' for all the function cares...it still calls the first parameter 'a'.
Parameter 'b' is optional (look at the function definition). If you don't send it, it gets a default value of 42.
+ 3
Yes it does help ! Thank you guys : )
+ 3
Yeah I should have kept going instead of starting crying. It becomes pretty clear afterwards in the tutorial ... My bad : /
+ 2
It's in : Functions > Default arguments