+ 1
Why this function doesn't work in C++?
I'm trying to increment integer named a with this function but actually dosen't work. I know i can use a++ or a=a+1 instruction but i wonder why this function dosen't work? https://code.sololearn.com/cWiGb4efGhr2/?ref=app
13 odpowiedzi
+ 3
Mohammad Razavi C++(void) has two passing methods: Pass by value and pass by reference.
**What is pass by value?**
Pass by value, uses the copy of the given parameter, for example, if a(consider it as the parameter passed to the method) is 6, it would make another copy of a and then use it in its function.
**What is pass by reference?**
Pass by reference gets the reference of the parameter passed to the method.. with pass by reference, the function will be able to modify the current variable itself.
The code you provided actually uses pass by value to the method increment, that's why it does not affect to the current variable. Pass by reference solves the problem.
+ 2
You need to return the function.
Like this:
#include <iostream>
using namespace std;
int increment(int a){
return ++a;
}
int main() {
int a = 10;
cout<< increment (a);
return 0;
}
+ 2
You've to take care of call by reference property.
+ 1
https://code.sololearn.com/c33RjTZE1dZC/?ref=app
You have to use pointer for it.. To pass by reference.
+ 1
Mohammad Razavi kinda something like that, that's called pass by value.
+ 1
Dragon RB
Thanks for your explanation! 🙏
+ 1
Mohammad Razavi You're welcome! If you wanna learn deeper about pass by value and pass by reference in C++, I've found and gathered some articles talking about it:
https://www.w3schools.com/cpp/cpp_function_reference.asp
https://www.ibm.com/docs/en/zos/2.4.0?topic=calls-pass-by-reference-c-only
https://www.ibm.com/docs/en/zos/2.4.0?topic=calls-pass-by-value
https://www.educative.io/answers/pass-by-value-vs-pass-by-reference
https://stackoverflow.com/questions/410593/pass-by-reference-and-value-in-c
+ 1
here is your solution!
https://code.sololearn.com/c8BQGZ8aImKV/?ref=app
0
You are passing it by value.
0
Dragon RB
Thank you!
Yeah it was correct but why previous function didn't work? What was the logical error?
I saw this code about pointers in youtube but i don't get the logic of that
Both of a s are integers and i put a integer value inside of the Function argument but it fails.Why?
0
Dragon RB
So you're saying for example if a=6
And function is fun(int a)
C++ will copy 6 into that function?
Even with this it should work like below:
increment(int 6)
6 = 6+1
0
Dragon RB
Thanks for your kindness 👍🙏