Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

วิธี Return หลายค่าจากฟังก์ชันใน C/C++

C/C++ ไม่ Return หลายค่าโดยตรง ใช้ Call by Address หรือ Call by Reference แทน

ตัวอย่าง: หารeturn Quotient และ Remainder พร้อมกัน

#include <stdio.h>

void div(int a, int b, int *quotient, int *remainder) {
    *quotient = a / b;
    *remainder = a % b;
}

int main() {
    int a = 76, b = 10, q, r;
    div(a, b, &q, &r);
    printf("Quotient: %d\nRemainder: %d\n", q, r);
    return 0;
}

ผลลัพธ์

Quotient: 7
Remainder: 6