简体   繁体   中英

What is the best way to return a string value from an int function?

Probably something very straightforward, but I have a recursive function, that returns either the element in an array that is a majority, or returns "None" if there is no majority.

if (count > size_of_input / 2) {
    return maj1;
} else if (count2 > size_of_input/2) {
    return maj2;
} else {
    return -1;
}

Now I want to have the function print "None" instead of -1 if it's the case that there is no majority.

In the main function I am printing these values like so:

printf("%d",merge_sort(&input[0], 0, 24));

How should I optimally go about it?

Apologies if it's not the best question.

There is no standard-compliant way to return a string from an int function. Returning -1 wouldn't work either, because -1 could be a legitimate majority element in an array of int .

One approach to do this is to return the value by setting the result by pointer, and returning a flag indicating a success:

bool find_majority(int data[], size_t length, int* resPtr) {
    ...
}

The caller would invoke your function as follows:

int res;
if (find_majority(array, array_length, &res)) {
    printf("Found: %d\n", res);
} else {
    printf("Not found\n");
}

How should I optimally go about it?

The optimal way would be break the original statement into parts rather than trying to wrap everything into one statement. There is possibly a way to do it like you are trying to do, but it is at best messy. I would strive for clarity over compactness. Here is some code to implement this below assuming -1 is a failure condition and that the values in input are non-negative (based on your description, although the domain here is a bit ambiguous):

int majority = merge_sort(&input[0], 0, 24);

if(majority == -1)
    printf("None");
else
    printf("%d",majority);

This is adding a few extra lines, but this is very clear and gets what you want done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM