+ 1
return vs cout in C++
int func(int x, int y) { x = 10; return (x+y); } int main () { int i = 0; int j = 5; i = func (j, i); cout << i << j; } I'm confused about how the return statement is used in the code above. I first assigned i = func(5,0) ----> have no idea what to do next... do I add 5 and 0 and re-assign i = 5? Also, where would I plug in the x = 10 in the second line? How does x and y relate to i and j? Is the final output provided by cout, return (x+y) or int func(int x, int y)? Totally lost.
3 Respuestas
+ 4
Solus Is this something you wrote?
Here are the answers to your questions:
1. The return statement is, well, returning the integer value 10 from func(5, 0).
2. func(5, 0) ignores the first argument as x is always reassigned the value 10. Therefore, func(5, 0) will return (10 + 0) instead of (5 + 0) which is then assigned to int i in the main function.
3. You asked "where do you plug in x = 10 in the second line?" Did you mean "why" instead of "where"? Assuming you meant "why", I would say you would know better than me if you wrote this code. 😉 However, if you grabbed this code from code challenges, then it's likely the author was trying to make this a tricky question. 🤷♂️
4. The values j and i are passed as the input arguments x and y for func(x, y). Notice the reverse order of j and i, which map to x and y as illustrated below:
x = j
y = i
5. i is assigned 10 as the return value from func(5, 0).
j is still 5.
cout prints 10, then 5 without spaces which appears as: 105
+ 3
@David Carroll As a beginner, how would I know that the return statement return (x+y) will return the integer value 10 from i = func(5, 0)?
If i = 10, then cout will indeed output 105. But I still don't really understand how i = 10 came to be...
This was a challenge Q that I got wrong. I'm trying to learn from my mistakes. Thank you for the explanation.
+ 1
Return type returns the value It doesn't print value means you can assign returned value to other variable.Whereas Cout Simply prints text.