C/C++ में फंक्शन सीधे केवल एक मान रिटर्न कर सकता है। मल्टीपल मानों के लिए: पॉइंटर्स, रेफरेंस (C++), स्ट्रक्चर, या ग्लोबल वेरिएबल्स उपयोग करें।
विधि 1: कॉल बाय एड्रेस (पॉइंटर्स) - C और C++
#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;
int q, r;
div(a, b, &q, &r);
printf("Quotient: %d, Remainder: %d\n", q, r); // 7, 6
return 0;
}
विधि 2: कॉल बाय रेफरेंस (C++ केवल)
#include <iostream>
using namespace std;
void div(int a, int b, int "ient, int &remainder) {
quotient = a / b;
remainder = a % b;
}
int main() {
int q, r;
div(76, 10, q, r);
cout << "Quotient: " << q << ", Remainder: " << r << endl;
return 0;
}
विधि 3: स्ट्रक्चर रिटर्न
#include <stdio.h>
struct DivResult {
int quotient;
int remainder;
};
struct DivResult div(int a, int b) {
return (struct DivResult){a / b, a % b}; // कंपाउंड लिटरल (C99)
}
int main() {
struct DivResult res = div(76, 10);
printf("Quotient: %d, Remainder: %d\n", res.quotient, res.remainder);
return 0;
}
विधि 4: std::pair / std::tuple (C++11+)
#include <tuple> #include <iostream> std::pairdiv(int a, int b) { return {a / b, a % b}; } // या structured binding (C++17) auto [q, r] = div(76, 10);
विधि 5: आउटपुट पैरामीटर पैटर्न (कॉमन)
// एरर कोड रिटर्न, आउटपुट पैरामीटर्स में परिणाम
int div(int a, int b, int *q, int *r) {
if (b == 0) return -1; // एरर
*q = a / b;
*r = a % b;
return 0; // सफलता
}
तुलना
| विधि | C | C++ | नोट्स |
|---|---|---|---|
| पॉइंटर आउटपुट | ✓ | ✓ | NULL चेक जरूरी |
| रेफरेंस आउटपुट | ✗ | ✓ | क्लीनर सिंटैक्स |
| स्ट्रक्चर रिटर्न | ✓ | ✓ | कॉपी एलिजन (RVO) ऑप्टिमाइज़ |
| std::tuple/pair | ✗ | ✓ | जेनेरिक, structured binding |