[C#] ref : ์ฐธ์กฐ์— ์˜ํ•œ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ „๋‹ฌ

2021. 11. 3. 09:01

๋ฉ”์†Œ๋“œ์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ int a, int b์™€ ๊ฐ™์ด ์ •์˜ํ–ˆ์„ ๋•Œ

๊ฐ’์— ์˜ํ•œ ์ „๋‹ฌ(call by value)๋กœ ์ด๋ฃจ์–ด์ ธ

๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ์‚ฌ์šฉํ•œ ๋ณ€์ˆ˜ x, y๋Š” ๋ณต์‚ฌ๋˜์–ด a, b์— ๋“ค์–ด๊ฐ„๋‹ค.

๋”ฐ๋ผ์„œ x, y๊ฐ’์€ ๋ฐ”๋€Œ์ง€ ์•Š๋Š”๋‹ค.

class Calcul
    {
        public static int Plus(int a, int b)
        {
			...
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int x = 3;
            int y = 5;
            int result = Calcul.Plus(x, y);
        }
    }

 

๋งค๊ฐœ ๋ณ€์ˆ˜๊ฐ€ ๋ฉ”์†Œ๋“œ์— ๋„˜๊ฒจ์ง„ ์›๋ณธ ๋ณ€์ˆ˜๋ฅผ ์ง์ ‘ ์ฐธ์กฐํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด

์ฐธ์กฐ์— ์˜ํ•œ ์ „๋‹ฌ(call by reference)์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ref๋ฅผ ์„ ์–ธํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

๋ฉ”์†Œ๋“œ๋ฅผ ์„ ์–ธํ•  ๋•Œ, ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ๋ชจ๋‘ ref ํ‚ค์›Œ๋“œ๋ฅผ ๋ณ€์ˆ˜ ์•ž์— ๋ถ™์—ฌ์ค˜์•ผํ•œ๋‹ค.

 class Calcul
    {
        public static int Plus(ref int a, ref int b)
        {
			...
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int x = 3;
            int y = 5;
            int result = Calcul.Plus(ref x, ref y);
        }
    }

 

728x90

BELATED ARTICLES

more