What is o/p of following code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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; }

21st May 2017, 7:49 AM
Hemant Makar
Hemant Makar - avatar
6 Answers
+ 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.
24th May 2017, 2:28 AM
Zeke Williams
Zeke Williams - avatar
+ 1
10
21st May 2017, 3:55 PM
Zeke Williams
Zeke Williams - avatar
+ 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; }
24th May 2017, 7:28 PM
Zeke Williams
Zeke Williams - avatar
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.
21st May 2017, 8:53 AM
Sano Bhai
0
actually I doubt for function declaration void func ( int & I,) I never seen this kind of function declaration
22nd May 2017, 7:06 PM
Hemant Makar
Hemant Makar - avatar
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!
24th May 2017, 7:07 PM
Hemant Makar
Hemant Makar - avatar