user2225940
user2225940

Reputation: 83

Creating int function which in case of an error can not return a valid int value

I am trying to create a function will return the value located in the struct. My issue is trying to figure out what I can return by the function if theInfo = NULL?

Below is what I have created so far. Is this possible to do?

int getTime(struct * theInfo){  
  if(theInfo != NULL){
      return theInfo->waitTime;
  }
  else{
    printf("getTime Patron is nonexistent\n");
    return(thePatron);
  }
}

Upvotes: 1

Views: 332

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You need to return two pieces of information - the number, and an indication of whether or not that number is valid. One way to do it is changing the signature of the function to indicate whether or not it returned anything, and in case when it does, stick that value in a variable. Here is an example of how you can do it:

// This function returns 1 or 0.
// 1 indicates success; 0 indicates failure
// If your compiler is up to C99 standard, use "bool" instead of "int" below
int getTime(struct * theInfo, int *result) {
    if(theInfo != NULL){
        *result = theInfo->waitTime;
        return 1;
    } else{
        // result stays unchanged
        return 0;
    }
}

Now you can use this new function like this:

int res;
if (getTime(&myInfo, &res)) {
    printf("getTime returned %d\n", res);
} else {
    printf("getTime Patron is nonexistent\n");
}

A less general alternative can be used when you do not need to return a full range of numbers. For example, if the valid time returned by your function is always positive, you could adopt a convention that uses negative numbers to indicate that there was an error. This approach is also valid, but it relies more on a convention, so a reader of your code would need to look through your function documentation to see what is going on.

Upvotes: 2

user995502
user995502

Reputation:

Just return -1. I am sure that wait time is always positive.

So return -1 if it is NULL and then check for -1

else{
    printf("getTime Patron is nonexistent\n");
    return -1;
  }


void someFunc() {
//...
   int wtime = getTime(astruct);
   if (wtime == -1)
       // error

//...
}

Upvotes: 2

LihO
LihO

Reputation: 42083

You could pass a pointer and return a boolean value indicating success:

bool getTime(MyStruct* info, int* time) {  
    if (info) {
        *time = info->waitTime;
        return true;
    }
    *time = 0;
    return false;
}

Then somewhere you would just call:

int time;
if (!getTime(info, &time)) {
    // TODO: retrieval of time failed
}

Upvotes: 2

Related Questions