Functions

by Kwang-Soo Hahn, [email protected]
Dept. of Computer Science, Kookmin University
910-4794, http://kshahn.kookmin.ac.kr


Objectives

FunctionÀÇ Á¤ÀÇ

return_type function_name (argument declarations)
{
     ¼±¾ð¹®

     ½ÇÇ๮
     
}

return_type

functionÀÌ returnÇÏ´Â dataÀÇ type.

Return °ªÀÌ ¾øÀ¸¸é void ÇüÀ» »ç¿ëÇÏ°í »ý·«Çϸé int·Î °£ÁֵȴÙ.

Return °ªÀº return ¹®À» »ç¿ëÇÏ¿© Àü´ÞÇÑ´Ù.

function_name

C identifier·Î functionÀÌ ¼öÇàÇÏ´Â ±â´É¿¡ ¾Ë¸Â´Â À̸§À» »ç¿ëÇÑ´Ù.

argument declarations

0 ¶Ç´Â ±× ÀÌ»óÀÇ ¸Å°³º¯¼ö (formal parameters) Á¤ÀÇ.

Function ³»ºÎ¿¡¼­´Â local º¯¼ö·Î »ç¿ëµÈ´Ù.

¾øÀ» °æ¿ì¿¡µµ ( )¸¦ »ý·«ÇÒ ¼ö ¾ø´Ù.


Library functions

¸¹ÀÌ »ç¿ëµÇ´Â functionµéÀ» ÀÛ¼ºÇÏ¿© library·Î ¸¸µé¾î ÇÁ·Î±×·¥ ÀÛ¼º ½Ã function prototypeÀÌ Á¤ÀÇµÈ header¸¦ includeÇÏ¿© »ç¿ëÇÑ´Ù.

¿¹) Mathematical functions : <math.h>

double sin (double);

cos(x), tan(x), atan2(y, x), exp(x), log(x), log10(x), pow(x, y), sqrt(x), fabs(x)


Recursive function

Á÷Á¢ ¶Ç´Â °£Á¢ÀûÀ¸·Î ÀÚ±â ÀÚ½ÅÀ» È£ÃâÇÏ´Â functionÀ¸·Î º¸Åë stack memory¸¦ ¸¹ÀÌ »ç¿ëÇÏ¸ç ¹Ýº¹ÀûÀÎ function call·Î ÀÎÇÏ¿© ¼öÇà ¼Óµµ°¡ ´À¸®³ª ±¸Á¶°¡ °£°á, ¸íÈ®ÇÏ¿© ÇÁ·Î±×·¥ ÀÛ¼ºÀ» ¿ëÀÌÇÏ°Ô ÇÑ´Ù.

¿¹) FactorialÀ» °è»êÇÏ´Â recursive function (fact.c)

          long Factorial(int n)
          {
             if (n > 2)
                return (n * Factorial(n - 1));
             else
                return 1L;
          }

Function-calling process

fact = Factorial(2 + 3);

  1. È£Ãâ ÇÔ¼ö (calling function)ÀÇ °¢ argument °ªÀ» °è»êÇÑ´Ù. (2 + 3 ==> 5)
  2. °¢°¢ÀÇ argument °ªÀÌ ÇÇÈ£Ãâ ÇÔ¼ö (called function)ÀÇ formal parameter variableµé¿¡ ¼ø¼­´ë·Î Àü´ÞµÈ´Ù. ÀÌ °æ¿ì ÇÊ¿ä½Ã Çü º¯È¯(type casting)ÀÌ ¼öÇàµÈ´Ù. (5 ==> n)
  3. Function bodyÀÇ ¹®µéÀÌ return¹®À» ¸¸³¯ ¶§±îÁö ¼öÇàµÈ´Ù.
  4. Return¹®ÀÇ expressionÀÌ evaluate µÇ¾î calling functionÀ¸·Î µÇµ¹·Á Áø´Ù. (ÇÊ¿ä½Ã type conversion ¼öÇà)
  5. ÇÔ¼ö¸¦ È£ÃâÇØ »ç¿ëÇÑ ÇÁ·Î±×·¥¿¡¼­´Â µÇµ¹·ÁÁø °ªÀ¸·Î function callÀ» ´ëÄ¡ÇÏ¿© ÇÁ·Î±×·¥À» °è¼Ó ¼öÇàÇÑ´Ù.

Parameter (¸Å°³ º¯¼ö) °ªÀÇ Àü´Þ

C¿¡¼­ address operator¸¦ »ç¿ëÇÏ¿© call by reference ¹æ½Ä ¸ð¹æÀÌ °¡´ÉÇÏ´Ù.

void swap(int x, int y)

void swap(int *x, int *y)



[ Table Of Contents | Previous Chapter | Next Chapter]