http://www.hackerschool.org/HS_Boards/zboard.php?id=Free_Lectures&no=8565 [º¹»ç]
¡Ø¾î¼Àºí¸®¾îÀÇ °üÁ¡¿¡¼ ¹Ù¶óº¸¸é ±ÛÀÌ ³Ê¹« ±æ¾îÁö´Ï C¾ð¾îÀÇ °üÁ¡¿¡¼ ¹Ù¶óº¸°Ú½À´Ï´Ù.
Á÷¿ªÇÏÀÚ¸é °ª¿¡ ÀÇÇÑ È£Ãâ°ú ÂüÁ¶¿¡ ÀÇÇÑ È£ÃâÀ̶ó°í Çؼ®ÇÒ ¼ö ÀÖ´Ù.
ÀÏ´Ü µÎ°³ÀÇ ¼Ò½º¸¦ º¸¿©ÁÖ°Ú´Ù.
=================================
// Call by vaule
#include <stdio.h>
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
int main(void)
{
int a = 10;
int b = 20;
swap(a, b);
printf("a : %d, b : %d\n", a, b);
return 0;
}
=================================
À§ ¼Ò½ºÀÇ °°Àº °æ¿ì mainÇÔ¼ö ³»¿¡¼ intÇü º¯¼ö a¿Í b¸¦ swapÇÔ¼öÀÇ ÀÎÀÚ·Î ³Ñ°å´Ù.
Çٽɸ¸ ¿ä¾àÇؼ ¸»ÇÏÀÚ¸é mainÇÔ¼ö º¯¼ö¸¦ swapÇÔ¼ö¿¡ ³Ñ±ä´Ù ÇÏ´õ¶óµµ
mainÇÔ¼ö ³»ºÎÀÇ ÀÎÀÚ¿Í swapÇÔ¼öÀÇ ¸Å°³º¯¼ö´Â ¿ÏÀüÈ÷ º°°³¶ó°í »ý°¢Çصµ ¹«¹æÇÏ´Ù.
±×·¡¼ À§ ¼Ò½º¸¦ Ãâ·ÂÇϸé a : 10, b : 20À̶ó°í °á°ú°¡ ³ª¿Â´Ù.
±×·¸´Ù¸é mainÇÔ¼ö ³»ºÎÀÇ º¯¼ö a¿Í b¸¦
swapÇÔ¼ö ³»ºÎ¿¡¼ º¯°æ½Ãų·Á¸é ¾î¶»°Ô ÇØ¾ß ÇÒ±î?
¿©±â¼ ÇÊ¿äÇÑ °³³äÀÌ ¹Ù·Î Call by referenceÀÌ´Ù!
=================================
// Call by reference
#include <stdio.h>
void swap(int *pA, int *pB)
{
int temp;
temp = *pA;
*pA = *pB;
*pB = temp;
}
int main(void)
{
int a = 10;
int b = 20;
swap(&a, &b);
printf("a : %d, b : %d\n", a, b);
return 0;
}
===============================
¹º°¡ ´Ù¸£°Ô º¸À̴°¡?
Æ÷ÀÎÅÍÀÇ °³³äÀ» ¾È ´Ù¸é ÀÌÇØÇÏ´Â °ÍÀÌ ½±´Ù.
mainÇÔ¼ö ³»ºÎÀÇ swapÇÔ¼öÀÇ Àü´Þ°ªÀ¸·Î ¿Ö a, b¶ó°í ¾È ÇÏ°í &a, &b¶ó ÇßÀ»±î?
&(¾ÚÆÛ¼¾Æ®)¿¬»êÀÚ´Â ÁÖ¼Ò¸¦ ÀǹÌÇÑ´Ù.
swapÇÔ¼ö ³»ºÎ¸¦ º¸¸é *(¿¡½ºÅ͸®½ºÅ©)¿¬»êÀÚ¸¦ »ç¿ëÇϴµ¥
*´Â Æ÷ÀÎÅÍÀÇ °³³ä ¿¬»êÀÚ·Î *a¶ó°í Çϸé
a°¡ °¡¸®Å°´Â º¯¼ö¸¦ ÀǹÌÇÏ°Ô µÈ´Ù.
Áï, swapÇÔ¼öÀÇ ¸Å°³º¯¼ö¿Í mainÇÔ¼öÀÇ º¯¼ö°¡ ¼·Î "¿¬°á"ÀÌ µÇ¾î¼
a¿Í bÀÇ °ªÀÌ º¯°æÀÌ µÈ´Ù´Â °Ô Call by referenceÀÇ °³³äÀÌ´Ù.
(ÇÊÀÚ°¡ ¾´ ÀÌ ±ÛÀ» ÀÌÇØÇÏ·Á¸é Æ÷ÀÎÅ͸¦ ÀÌÇØÇÏ°í ÀÖ¾î¾ßÇÑ´Ù.) |
Hit : 1630 Date : 2023/01/15 02:35
|