开发者

Optimized way of Error handling in C Embedded

开发者 https://www.devze.com 2023-04-01 23:33 出处:网络
Basic question开发者_C百科 but wanted to know optimized way of doing it.. It is a code block for a close routine having multiple process to close. In all the cases, it should try to close all the proc

Basic question开发者_C百科 but wanted to know optimized way of doing it.. It is a code block for a close routine having multiple process to close. In all the cases, it should try to close all the processes and stages, but keep the failures value to return back.

Error_code result=PASS;
<some code>
for i 1 to 10
 if((result = operation())!=PASS)
   PRINT "FAILURE"
 done    
 if((result = operation())!=PASS)
   PRINT "FAILURE"
for i 1 to 10
 if((result = operation())!=PASS)
   PRINT "FAILURE"
 done    

return result;

now the issue is if last iteration is Pass, then it return a PASS, Since the operation should be running for all 10 iterations, and in case of failure, it is just that we need to return the Error code. Since it can virtually have 100 failures, I write the code like this:-

Error_code result=PASS;
Error_code tresult=PASS;
for i 1 to 10
 if((result = operation())!=PASS) {
   tresult = result;
   PRINT "FAILURE"
 }
 if((result = operation())!=PASS) {
   tresult = result;
   PRINT "FAILURE"
}
for i 1 to 10
 if((result = operation())!=PASS)
  tresult = result;
  PRINT "FAILURE"
 done    

if(tresult != result)
 result = tresult;

return result;

Is it the only optimized solution, or we can do better in this. I can't use flag, as it has more than 100 error variables.. Suggest any better way..


You need to dynamically allocate space for each error code in a linked list or array and then pass the list back to whatever needs to know the results.

You could either have a code for each process being closed and include the "OK" cases in there, or you could include the process ID and the error code together and only include them when there is an error.

For example:

errorList = NULL;
for i 1 to 10
 if((result = operation())!=PASS) {
  appendToList(errorList, i, result)
 }
if(errorList != NULL) {
 result = ERROR;
} else {
 result = PASS;
}
return result;

(Note: Although you've said you're writing in C, your code snippet looks more like pseudo code, so that's how I've addressed it here. You'd need to write the appropriate code to append the error code to your list).


If all you need to know is whether any of your iterations failed, you can use the ++ operator:

int result = 0;

for i 1 to 10
if(operation() != PASS)
    PRINT "FAILURE"
    result++;
done    

return (result == 0 ? PASS : ERROR);
0

精彩评论

暂无评论...
验证码 换一张
取 消