Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> सी प्रोग्रामिंग

C/C++ में फंक्शन से मल्टीपल वैल्यूज़ रिटर्न करना


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 &quotient, 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::pair div(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;  // सफलता
}

तुलना

  1. - JavaScript फंक्शन से स्ट्रिंग कैसे लौटाएं?

    JavaScript फंक्शन से स्ट्रिंग लौटाने के लिए JavaScript में return स्टेटमेंट का उपयोग करें। उदाहरण return स्टेटमेंट का उपयोग करके स्ट्रिंग लौटाना सीखने के लिए निम्न कोड चलाएं: <html> <head> <script> function concatenate(name, subject) { var val; val = na

  1. - JavaScript फंक्शन से मान कैसे लौटाएं?

    JavaScript फंक्शन से मान लौटाने के लिए JavaScript में return स्टेटमेंट का उपयोग करें। मान लौटाना सीखने के लिए निम्न कोड चलाएं: उदाहरण <html> <head> <script> function concatenate(name, age) { var val; val = name + age; return val; } f

  1. जावास्क्रिप्ट फंक्शन से ऑब्जेक्ट कैसे रिटर्न करें? जावास्क्रिप्ट फंक्शन से ऑब्जेक्ट कैसे रिटर्न करें?

    जावास्क्रिप्ट फंक्शन से ऑब्जेक्ट रिटर्न करने के लिए, return स्टेटमेंट का उपयोग this कीवर्ड के साथ करें।उदाहरणजावास्क्रिप्ट फंक्शन से ऑब्जेक्ट रिटर्न करना सीखने के लिए निम्नलिखित कोड चलाएं:<html>    <head>       <script>          var

© कॉपीराइट https://in.wsxdn.com सर्वाधिकार सुरक्षित
विधिCC++नोट्स
पॉइंटर आउटपुट✓✓NULL चेक जरूरी
रेफरेंस आउटपुट✗✓क्लीनर सिंटैक्स
स्ट्रक्चर रिटर्न✓✓कॉपी एलिजन (RVO) ऑप्टिमाइज़
std::tuple/pair✗✓जेनेरिक, structured binding