ในที่นี้เราจะมาดูกันว่าฟังก์ชัน C ชนิดต่างๆ มีอะไรบ้างตามค่าที่ส่งกลับและอาร์กิวเมนต์
ดังนั้นฟังก์ชันสามารถรับอาร์กิวเมนต์หรือไม่มีการรับค่าใด ๆ ในทำนองเดียวกัน ฟังก์ชันสามารถส่งคืนบางสิ่งได้ มิฉะนั้น จะไม่ส่งคืนสิ่งใดเลย เราจึงจำแนกได้เป็น 4 ประเภท
- ฟังก์ชันที่ไม่มีอาร์กิวเมนต์และไม่มีประเภทส่งคืน
- ฟังก์ชั่นที่ไม่มีอาร์กิวเมนต์และส่งกลับบางสิ่ง
- ฟังก์ชันที่รับอาร์กิวเมนต์แต่ไม่ส่งคืนใดๆ
- ฟังก์ชันที่รับอาร์กิวเมนต์และส่งคืนบางสิ่งด้วย
ตัวอย่าง
#include <stdio.h>
void my_function() {
printf("This is a function that takes no argument, and returns nothing.");
}
main() {
my_function();
} ผลลัพธ์
This is a function that takes no argument, and returns nothing.
ในที่นี้ ฟังก์ชันนี้จะไม่รับอาร์กิวเมนต์อินพุตใดๆ และประเภทการส่งคืนจะเป็นโมฆะ ดังนั้นจึงไม่คืนค่าใดๆ
ตัวอย่าง
#include <stdio.h>
int my_function() {
printf("This function takes no argument, But returns 50\n");
return 50;
}
main() {
int x;
x = my_function();
printf("Returned Value: %d", x);
} ผลลัพธ์
This function takes no argument, But returns 50 Returned Value: 50
ในที่นี้ ฟังก์ชันนี้ไม่ได้ใช้อาร์กิวเมนต์อินพุตใดๆ แต่ประเภทการส่งคืนเป็น int ค่านี้จะคืนค่ากลับมา
ตัวอย่าง
#include <stdio.h>
void my_function(int x) {
printf("This function is taking %d as argument, but returns nothing", x);
return 50;
}
main() {
int x;
x = 10;
my_function(x);
} ผลลัพธ์
This function is taking 10 as argument, but returns nothing
ฟังก์ชันนี้รับอาร์กิวเมนต์อินพุต แต่ประเภทการส่งคืนเป็นโมฆะ ดังนั้นจึงไม่คืนค่าใดๆ
ตัวอย่าง
#include <stdio.h>
int my_function(int x) {
printf("This will take an argument, and will return its squared value\n");
return x * x;
}
main() {
int x, res;
x = 12;
res = my_function(12);
printf("Returned Value: %d", res);
} ผลลัพธ์
This function is taking 10 as argument, but returns nothing
ฟังก์ชันนี้รับอาร์กิวเมนต์อินพุตและคืนค่าด้วย