08. 함수(ref) — 웹툰PD 지망생 : 정민재
08. 함수(ref)
●/섹션 2. 코드의 흐름 제어

08. 함수(ref)

728x90
using System;

namespace Csharp
{
    class Program
    {       
        static void HelloWorld()
        {
            Console.WriteLine("Hello World");
        }
        static void Main(string[] args)
        {
            HelloWorld();
        }
    }
}

 

using System;

namespace Csharp
{
    class Program
    {       
        static int Add(int a, int b)
        {
            int result = a + b;
            return result;
        }
        static void Main(string[] args)
        {
            //빨간 줄이 뜬다.
            Add();
        }
    }
}

 

using System;

namespace Csharp
{
    class Program
    {       
        static int Add(int a, int b)
        {
            int result = a + b;
            return result;
        }
        static void Main(string[] args)
        {
            //빨간 줄이 뜬다. 꼭 매개변수를 넣자.
            Add(4, 5);
        }
    }
}
using System;

namespace Csharp
{
    class Program
    {       
        static int Add(int a, int b)
        {
            int result = a + b;
            return result;
        }
        static void Main(string[] args)
        {
            //빨간 줄이 뜬다. 꼭 매개변수를 넣자.
            Add(4, 5);

            int result = Add(4, 5);

            Console.WriteLine(result);
        }
    }
}

 

using System;

namespace Csharp
{
    class Program
    {       
        static void AddOne(int number)
        {
            number = number + 1;
        }
        static void Main(string[] args)
        {
            int a = 0;

            AddOne(a);

            Console.WriteLine(a);
        }
    }
}

 

아니, 왜 0이지....?

 

함수식들로만 보면 1이 나오는게 정상일거 같은데...!

 

 

사실 메모리가 다르기 때문...!

 

실제 a의 메모리를 가져오고 싶으면

 

ref(레퍼런스)를 해야한다.

 

using System;

namespace Csharp
{
    class Program
    {       
        static void AddOne(ref int number)
        {
            number = number + 1;
        }
        static void Main(string[] args)
        {
            int a = 0;

            AddOne(ref a);

            Console.WriteLine(a);
        }
    }
}

728x90

' > 섹션 2. 코드의 흐름 제어' 카테고리의 다른 글

10. 오버로딩  (0) 2021.07.10
09. ref, out  (0) 2021.07.10
07.break, continue(흐름 제어)  (0) 2021.07.10
06. for  (0) 2021.07.10
05. while  (0) 2021.07.10