+ 1

Passing an argument by reference

Can anyone give insight on how the input of this code is "1220"? I understand x is 34 and adding that gives 68 but I get lost on the multiplying. It was a question I got wrong in a coding challenge and I want to understand my mistake. Thank You. static void Func (ref int x) { x = x + x * x; } static void Main (string [] args) { int a = 3; int b = 4; Func (ref a); Func (ref b); Console.Write(a + "" + b); }

7th Jul 2018, 9:45 PM
D Murry
D Murry - avatar
4 odpowiedzi
+ 2
I dont know C# but i am sure that x in Func its same like a reference in C++. Anyway Func get an int by reference and make changes to it and because its a reference, changes wil be maded original passed variable. In first call you pass 'a' (value 3) then "Func" make: x= 3+3*3= 12 then x in Func its equal to 12 BUT because x its a reference to a in Main, a (Main) its same that x (Func). Returned by function, now 'a' has value 12 then you call Func with 'b' and same happen but this time your "edit" will be maded on 'b' variable that after call of Func it wil have 20 value (4+4*4=20). Then at this point you will have: a= 12 b= 20 The rest its easy
7th Jul 2018, 9:55 PM
KrOW
KrOW - avatar
+ 2
First calculating a = 3 + 3*3, which is 12, then b = 4 +4*4, which is 20.Then in result you have to concatenate a and b like strings => "12" +"20". So the answer is 1220.
7th Jul 2018, 9:54 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
Thank you I was breaking the problem down in the wrong form
7th Jul 2018, 10:12 PM
D Murry
D Murry - avatar
0
👍👍👍
7th Jul 2018, 10:17 PM
KrOW
KrOW - avatar