+ 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); }
4 Réponses
+ 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)
+ 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);
}
+ 3
Pass by value is the reason
+ 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)
..
}