Can someone explain this why output is not 9 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone explain this why output is not 9

static void Sqr(int x) { x = x * x; } static void Main(string[] args) { int a = 3; Sqr(a); Console.WriteLine(a); }

24th Feb 2021, 6:36 PM
Codelearner
4 Answers
+ 5
The value of 'a' is copied, so you work with a copy in your function 'Sqr'. (btw, if you can avoid tagging C and C++ when it is a C# issue, it would be great)
24th Feb 2021, 6:40 PM
Théophile
Théophile - avatar
+ 5
Agreed with Theophile 👍 If you want it to work as you desired, then you need to pass <a> by reference. static void Sqr(ref int x) { x *= x; } static void Main(string[] args) { int a = 3; Sqr(ref a); Console.WriteLine(a); }
24th Feb 2021, 6:50 PM
Ipang
+ 3
Pass by value is the reason
24th Feb 2021, 7:36 PM
Danny Wanyoike
Danny Wanyoike - avatar
+ 2
Because you're passing (a) argument by value in the main method, It's like taking a copy of the local variable (a) and passing It as an argument to (Sqr) method. Thus, you don't update the local variable (a) but a copy of It. But, If you want the result to be 9, you should add (ref) keyword before the parameter (x) and also before the argument (a) to be like this: static void Sqr(ref int x) { ... } static void Main(string [] args) { ... int a = 3; Sqr(ref a) .. }
24th Feb 2021, 11:49 PM
Mhd AlHaj Houssein
Mhd AlHaj Houssein - avatar