0
What is o/p of following code
void func(int &i) { i =100; } int main(){ int i = 10; func(i); cout << i; return 0; }
6 Antworten
+ 2
@HemantMakar void func (int &i) is a function declaration that takes the reference of the variable i, rather than copying the value, which would be like this: void func (int i). Passing a variable by reference allows the function to change the value of the variable in any scope.
For example:
void func (int &i) {
i *= 2;
}
void func2 (int i) {
i *= 2;
}
int main() {
int a = 3;
int b = 4;
func (a);
func2 (b);
cout << "a: " << a << "\nb: " << b << endl;
// outputs "a: 6
// b: 4"
return 0;
}
See how a's value was changed and b's was not? This is how passing by reference works.
+ 1
10
+ 1
Essentially that is what is happening when you declare it like this: void func (int &i). You are passing the 'address' of the variable. It is almost the same as this: void func2 (int* i). The difference will be how you call it and using pointer syntax in func2. You will call it like this:
int a;
func2 (&a);
You have to pass in the address by using '&'. Also, if you look at my previous example, you will have to change the value inside the function like this:
void func2 (int* i) {
(*i) *= 2;
}
0
The best option is to try it yourself if you have C compiler installed. If you do not then search in internet where you can run cpp codes and check the result.
0
actually I doubt for function declaration
void func ( int & I,)
I never seen this kind of function declaration
0
Thanks for the response
But I never saw function declaration like this
void func( int &i) in c/cpp language.
As per your ans below function declaration is same
void func( int * i)
void func(int &i)
correct me if I am wrong!