0
can someone explain me why is 'a' not incrementing in the code given below? Thanks
#include <iostream> using namespace std; int increament(int a){ return a++; } int main(){ int a = 9; increament(a); cout<<a; return 0; }
1 Antwort
+ 2
@Akash Kumar you are wrong.Even if you return ++a it will give the same result.
The main reason is,
you are passing the value of a to the function not the reference.So if you use a++ or ++a it won't increment the value of a inside the main function.
So you can pass by reference.If you pass the value by reference ,there's no need to use int return type of the function.You can use void.
Here is an example:
(sorry my code playground is not working.So I have to give the code in description):
#include <iostream>
using namespace std;
void increament(int &a){
a++;
}
int main(){
int a = 9;
increament(a);
cout<<a;
return 0;
}