C++ | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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;}

25th May 2024, 4:44 AM
Mohammadamin
Mohammadamin - avatar
6 Antworten
+ 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
25th May 2024, 5:18 AM
A͢J
A͢J - avatar
+ 8
because variables are pass by value not pass by reference by default, we have to use '&' to make it pass by reference
25th May 2024, 7:43 AM
Alhaaz
Alhaaz - avatar
+ 3
Bob_Li, Mohammadamin is asking this, cuz it a question from C++ Challenge
25th May 2024, 10:05 AM
Alhaaz
Alhaaz - avatar
+ 2
you want this if you want 4: (you don't even need the return) void f(int& k){ k++; }
25th May 2024, 9:46 AM
Bob_Li
Bob_Li - avatar
+ 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
26th May 2024, 12:05 PM
Mallikarjun M
Mallikarjun M - avatar
0
Mallikarjun M yes, that's the usual way to do it.
26th May 2024, 12:47 PM
Bob_Li
Bob_Li - avatar