שפת C/פונקציות: הבדלים בין גרסאות בדף

תוכן שנמחק תוכן שנוסף
שורה 133:
</source>
הפקודה return גורמת ליציאה מהפונקציה (בלי ערך מוחזר בפונקציה זו). אם הפקודה מתבצעת, אז שאר הפקודות עד סוף הפונקציה אינן מתבצעות.
 
==קריאה לפונקציה==
קריאה לפונקציה נכתבת כך:
<source lang = "c">
<function_name>(<values>)
</source>
כאשר function_name היא שם הפונקציה, ו-values הם הערכים שיש להשים למשתניה. אם הפונקציה אינה מקבלת ארגומנטים, פשוט רושמים כך:
<source lang = "c">
<function_name>()
</source>.
 
להלן דוגמה לקריאה לפונקציה celsius_to_fahrenheit:
<source lang = "c">
#include <stdio.h>
 
float celsius_to_fahrenheit(float celsius)
{
return 1.8 * celsius + 32;
}
 
 
int main()
{
int f;
f = celsius_to_fahrenheit(3);
printf("%d", f);
return 0;
}
</source>
השורה
<source lang = "c">
f = celsius_to_fahreneit(3);
</source>
קוראת לפונקציה עם הערך 3. כעת הפונקציה מתחילה לפעול, ובתוך הפוקנציה, המשתנה celsius הוא בעל הערך 3. כשהפונקציה מגיעה לשורה
<source lang = "c">
return 1.8 * celsius + 32;
</source>
חוזר רצף התוכנית לשורה שקראה לה. במקרה זה, הערך המוחזר מהפונקציה יושם למשתנה f.
 
אם נחזור שוב לתוכנית המקורית שרשמנו בתחילת הפרק, נוכל לכתוב אותה כך:
<source lang = "c">
#include <stdio.h>
 
float celsius_to_fahrenheit(float celsius)
{
return 1.8 * celsius + 32;
}
 
 
int main()
{
int c, f;
 
for(c = 0; c <= 40; c += 4)
{
f = celsius_to_fahrenheit(c);
printf("%d in Celsius is %d in Fahrenheit\n", c, f);
}
 
printf("Enter degrees in Clesius: ");
scanf("%d", &c);
f = celsius_to_fahrenheit(c);
printf("This is %d in Fahrenheit\n", f);
return 0;
}
</source>
למעשה, כפי שכתובה התוכנית כעת, נוכל אפילו לוותר על חלק מהמשתנים, ולכתוב אותה בצורה קצרה יותר כך:
<source lang = "c">
#include <stdio.h>
 
float celsius_to_fahrenheit(float celsius)
{
return 1.8 * celsius + 32;
}
 
 
int main()
{
int c;
 
for(c = 0; c <= 40; c += 4)
printf("%d in Celsius is %d in Fahrenheit\n", c, celsius_to_fahrenheit(c));
 
printf("Enter degrees in Clesius: ");
scanf("%d", &c);
printf("This is %d in Fahrenheit\n", celsius_to_fahrenheit(c));
return 0;
}
</source>
 
==פונקציות שכבר ראינו==