Mariska
Mariska

Reputation: 1949

Handling possible errors in C in a simple function

I have the following code:

// global variables
count = 0;
char arr[50][5];

main(){
   // do something
}

init(){
   count = 0;
   memset (arr, 0, sizeof(arr));
}

I need to return 1 if init() is successful, but 0 if not. However, I can't see how init() can technically fail. How should I implement this error handler in init()?

Upvotes: 1

Views: 31

Answers (1)

cnicutar
cnicutar

Reputation: 182794

There are 2 issues:

  • You don't need to return anything if you don't want to, just make the function void
  • Your init function is not needed as arr is already 0-initialized since it has static storage (global variable).

EDIT

basically main() can modify count and arr, and at some point i need to re-initialize the global variables using init().

If the function can be called later on it would be useful to call it "reset", "reinit", "clear" etc. "init" makes the reader think it is only called once, at the beginning

According to the write-up i have to return 1 or 0 in init() depending on whether there's an error...

In that case just say:

/* XXX No other return code is possible. */
return 0;

Upvotes: 1

Related Questions