通过c中的函数返回两个不同类型的值



我们可以通过c中的函数返回两个值吗?

例如:在这里,我试图构建一个函数,如果有没有多数元素,则返回,如果有,则返回(true,x(wheras x多数元素,否则,返回(false,0(

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
// Fonction qui verifie si il y a un element majoritaire ou pas 
//dans une liste en utilisant un algorithme recursive

int nbr_occ(int A[], int n, int x)
{
int c=0, i;

for(i=0;i<n; i++)
{
if (A[i]==x) c++;
}
return c;
}
(_Bool , int) majoritaire (int A[], int i, int j)
{
bool rx, ry;
int x, y;
if(i=j) return (true, A[i]);
(rx, x) = majoritaire (A, i, (i+j)/2) ;
(ry, y) = majoritaire (A, (i+j)/2 + 1, j);

if (rx=false && ry=false)
return (false, 0)    ;
if (rx= true && ry=true)
{
if( x=y ) return (vrai, x)
else if ( nbr_occ(x) > (i-j)/2 ) return (true, x);
else if ( nbr_occ(y) > (i-j)/2 ) return (true, y);
else return (false, 0);
}
else if(rx=true)
{
if ( nbr_occ(x) > (i-j)/2) return (true, x);
else return (false, 0);
}
else if (ry=true)
{
if( nbr_occ(x) > (i-j)/2 ) return (true, y);
else return ( false,0);
}
}```

请参阅以下代码,说明如何返回struct。请根据您的目的进行调整,然后:

#include <stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct {
_Bool hasMajority;
int majority;
} majorityStruct;
majorityStruct myFunc(int a, int b) {
// just for demonstration:
majorityStruct result;
if (a == b) {
result.hasMajority = false;
result.majority = 0;
} else {
result.hasMajority = true;
result.majority = a-b;
}
return result;
}
int main() {
majorityStruct f = myFunc(20, 10);
printf("%d:%dn", f.hasMajority, f.majority);
return 0;
}

一个常见的习惯用法是正常返回其中一个值(通常是表示成功/失败的值(,并将另一个值存储在调用方提供的地址,即存储在通过引用传递的变量中。

_Bool majoritaire (int A[], int i, int j, int *result) {
// ...
if (has_majority) {
*result = m;
return true;
} else {
*result = 0; // or omit this, and document that 
// the result is only valid when true is returned
return false;
}
}
void other_function(void) {
int r;
if (majoritaire(A, i, j, &r)) {
printf("There is a majority and it is %dn", r);
} else {
printf("No majorityn");
}
}

根据我的经验,当只需要返回两个值时,这比struct方法更常见。