Return value undefined in C

Not sure if I'm thinking about this, but how do I return something undefined when the parameter is not in the range it should be?

I am trying to do:

uint64_t function(uint64_t Value, uint64_t N) {
   uint64_t result = 0;

   if (N > 0){
     //do something;
     return result;
   }
   else{
     return result is undefined;
   }
}

      

How do I return N: undefined?

+3


source to share


3 answers


One solution is to return the status and use the OUT parameter like this:

bool function(uint64_t Value, uint64_t N, uint64_t *result) {

   if (N > 0){
     //do something;
     *result = 31337;
     return true;
   }
   else{
     return false;
   }
}

      



Then, when you call this function, you check that the function returns true before using the result.

+5


source


For integer types, you can't.

There are exactly 2 64 possible values โ€‹โ€‹of the type uint64_t

, and each of them is a valid integer value.



In some cases, you can pick one value (perhaps UINT64_MIN

) that can be considered an error indication and return that, but this is not always practical.

Or you can revert the function to a success or failure result and pass the value uint64_t

back to the caller by other means, perhaps storing it with a pointer passed by the caller.

+3


source


Another option is to return the structure. This works better in C ++ (see Boost Optional), but here's the C version:

#include <stdio.h>
#include <stdbool.h>

struct optional_int {
    bool valid;
    int  value;
};

struct optional_int f(int x)
{
    struct optional_int result = {false, 0};
    if(x > 0 && x < 10) {
        result.valid = true;
        result.value = x * 1024;
    }
    return result;
}

int main()
{
    struct optional_int v;

    v = f(9);
    if(v.valid) {
        printf("Result is %d\n", v.value);
    }
    return 0;
}

      

+1


source







All Articles