+ 2
C++
Why is the output of this code equal to 3 and not 4???🤔🤔🤔 int f(int k){ k++; return k;} int main(){ int k{2}; k++; f(k); cout<<k;}
6 Réponses
+ 8
Because return value of f(int k) is not assigned to k
And k is a int which cannot have reference so output is 3
+ 8
because variables are pass by value not pass by reference by default, we have to use '&' to make it pass by reference
+ 3
Bob_Li, Mohammadamin is asking this, cuz it a question from C++ Challenge
+ 2
you want this if you want 4: (you don't even need the return)
void f(int& k){
k++;
}
+ 1
#include <iostream>
using namespace std;
int f(int k) {
k++;
return k;
}
int main() {
int k{2};
k++;
k = f(k);
cout<<k;
}
i have updated your code to assign the value returned by f() to k.
The following link takes you to C++ Online Compiler with our code
https://programguru.org/online-compiler/cpp?heading=&program=%23include%20%3Ciostream%3E%0Ausing%20namespace%20std%3B%0Aint%20f(int%20k)%20%7B%0A%20%20k%2B%2B%3B%0A%20%20return%20k%3B%0A%7D%0A%0Aint%20main()%20%7B%0A%20%20int%20k%7B2%7D%3B%0A%20%20k%2B%2B%3B%0A%20%20k%20%3D%20f(k)%3B%0A%20%20cout%3C%3Ck%3B%0A%7D
0
Mallikarjun M
yes, that's the usual way to do it.