[TIL-251212] 함수

데비·2025년 12월 15일

본과정

목록 보기
5/79

오늘 배운 내용

- 함수


- 함수란?

  • 특정 작업을 수행하도록 미리 만들어둔 코드의 묶음

- 인자, 매개변수(parameters)

데이터타입 변수명(인자값,매개변수)
{
	기능구현
}

- 반환값이 있는 경우와 없는 경우

- 반환값이 있는경우

DataType FuncName()
{
	return Data;
}

- 반환값이 없는경우

void FuncName()
{
	// 반환값이 없기 때문에 특정 기능 자체를 담당하는 함수가 됨
}

★ 매개변수 한정자 <-- 중요

- Call By Reference / Call By Value

Call By Reference : 함수 호출 시 원본의 메모리 주소를 전달
Call By Value : 함수 호출 시 복사본 생성

static void SwapNumbers2(ref int first, ref int second)
{
	// first, second는
    // 입력받은 인자의 데이터가 존재하는 메모리 주소를 전달 받음
    // call by reference
	int temp = first;
    first = second;
    second = temp;
}
static void SwapNumber1(int first, int second)
{
	// first, second는
    // 입력받은 인자의 "복사본"이 된다.
    // call by value
    int temp = first;
    first = second;
    second = temp;
}

- Ref (읽기/쓰기)

static void RefTest(ref int x)
{
	Console.WriteLine(x);  // 읽기
    x = 5; 				   // 쓰기
}

- In (읽기)

static void InTest(in int x)
{
	Console.WriteLine(x);	// 읽기
    x = 5;					// 쓰기(에러)
}

- Out (쓰기 : 반드시 써야 함)

  • out 키워드로 전달된 인자는 함수 내부에서 반드시 값을 할당 해야함
static void OutTest(out int x)
{
	// 에러(인자에 값을 할당하지 않음)
}
static void OutTest(out int x)
{
	Console.WriteLine(x); // 초기화 되기 전 읽기(에러)
    x = 5;				  // 쓰기
}

0개의 댓글