+2

Question about the output from a code

Why the outcome of this code is not 4? Am I missing something? #include <iostream> using namespace std; int f(int k){ k++; return k; } int main() { int k{2}; k++; /*k=3*/ f(k); /*inside the function, it has k++,so k should be 4(?!)*/ cout<<k; return 0; }

c++

11/21/2019 4:14:42 PM

汝風留名

2 Answers

New Answer

+5

Remember 2 things: 1) Pass by value does not change the value of the local variable (k in main() is unaffected) 2) You call your function but don't assign its return value anywhere so f(k) is sitting there with nowhere to go Thus k=3

+1

oh I missed that. Thx xD