+ 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

18th Aug 2023, 10:47 AM
Mohammad Razavi
Mohammad Razavi - avatar
12 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.
18th Aug 2023, 11:03 AM
Dragon RB
Dragon RB - avatar
+ 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; }
18th Aug 2023, 4:10 PM
Haider Ali Waris
Haider Ali Waris - avatar
+ 2
You've to take care of call by reference property.
19th Aug 2023, 6:32 AM
filibuster
filibuster - avatar
+ 1
https://code.sololearn.com/c33RjTZE1dZC/?ref=app You have to use pointer for it.. To pass by reference.
18th Aug 2023, 10:53 AM
Dragon RB
Dragon RB - avatar
+ 1
Mohammad Razavi kinda something like that, that's called pass by value.
18th Aug 2023, 11:09 AM
Dragon RB
Dragon RB - avatar
+ 1
Dragon RB Thanks for your explanation! 🙏
18th Aug 2023, 11:12 AM
Mohammad Razavi
Mohammad Razavi - avatar
20th Aug 2023, 10:01 AM
Alhaaz
Alhaaz - avatar
0
You are passing it by value.
18th Aug 2023, 10:54 AM
Dragon RB
Dragon RB - avatar
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?
18th Aug 2023, 10:57 AM
Mohammad Razavi
Mohammad Razavi - avatar
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
18th Aug 2023, 11:07 AM
Mohammad Razavi
Mohammad Razavi - avatar
0
Dragon RB Thanks for your kindness 👍🙏
18th Aug 2023, 11:51 AM
Mohammad Razavi
Mohammad Razavi - avatar