함수

댓글 0
댓글을 작성하려면 로그인이 필요합니다.
아직 댓글이 없습니다. 첫 번째 댓글을 작성해보세요.
코드 한 덩어리에 이름을 붙여두고, 필요할 때 그 이름으로 불러 쓰는 것 입니다.
변수가 데이터 별명을 지어주는거라면,
함수는 '기능'에 별명을 지어주는 것이다.
==문법 형식 : <접근 제한자> <반환형> 이름 ( ) { }==
ex) public int GetRandomNumber( )
{ return (int형의 결과값 반환) }
함수를 정의하는 쪽에 넘겨주는 값
static void Main()
{
int a = Sum(3, 21); // 매개변수 전달
}
static int Sum(int a, int b) // Main함수에서 받아온 3,21 매개변수가 a와 b에 들어간다.
{
int sum = a + b;
return sum;
}
| 표기 | 뜻 | 넘기기 전 값이 있어야 하는가 | 함수 안에서 값을 넣어야 하는가 |
|---|---|---|---|
| (없음) | 값을 복사해 넘깁니다 | 예 | 아니오 |
ref | 원본을 직접 다룹니다 | 예 | 아니오 |
out | 값을 받아 오기만 합니다 | 아니오 | 예 |
in | 원본을 보되 바꾸지 않습니다 | 예 | 넣을 수 없습니다 |
static void Main(string[] args)
{
int a = 5;
int b = 8;
Swap(a, ref b);
Console.WriteLine($"a = {a}, b = {b}");
}
static void Swap(int first, ref int second)
{
int temp = first;
first = second;
second = temp;
}
out은 값을 받아오는 것이 목적이기 때문에 넘기는 변수에 값이 들어있지 않아도 되지만,
함수 안에서는 반드시 값을 넣어야 합니다.
return은 결과를 하나만 돌려줄 수 있기 때문에 결과를 둘 이상 돌려주어야 할 때 사용합니다.
static void Main(string[] args)
{
int num = 5;
Foo(out num);
Console.WriteLine(num);
}
static void Foo(out int a)
{
Console.WriteLine(a); // 오류발생
a = 10;
}
in은 ref처럼 원본을 직접 볼 수 있지만, 함수 안에서 값을 바꾸는 것을 문법으로 막습니다.
in을 생략해도 됩니다. Foo(num)과 같게 동작합니다.static void Main(string[] args)
{
int num = 5;
Foo(in num);
Console.WriteLine(num);
}
static void Foo(in int a)
{
Console.WriteLine(a);
a = 10; // 오류발생
}
같은 이름의 함수를 여러 형태로 정의하는 것 입니다.
호출하는 쪽은 함수 이름만 기억하면 되고, 넘긴 값에 맞게 자동으로 골라집니다.
static void Main(string[] args)
{
float floatA = 3.55f;
float floatB = 2.6f;
int intA = 10;
int intB = 20;
int intC = 30;
Swap(floatA, floatB);
Swap(intA, intB);
Sum(intA, intB);
Sum(intA, intB, intC);
}
static void Swap(float first, float second)
{
float temp = first;
first = second;
second = temp;
}
static void Swap(int first, int second)
{
int temp = first;
first = second;
second = temp;
}
static int Sum(int a, int b)
{
int sum = a + b;
return sum;
}
static int Sum(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}
public static int GetValue(int a)
{
return a;
}
public static double GetValue(int a) // 오류: 매개변수 목록이 같습니다
{
return a;
}
자기 자신을 부르는 함수를 말합니다.
static void Main(string[] args)
{
Foo(5);
}
static void Foo(int count)
{
Console.WriteLine($"Foo 호출 count : {count}");
// 기저조건 설정 필요
if (count == 0)
{
Console.WriteLine("재귀 끝");
return; // 함수 끝
}
Foo(count - 1);
Console.WriteLine($"Foo 종료 count : {count}");
}

