Error handling - how to get rid of multiple flags?

E

Ed Davis

In the following code fragment, I only want to print an error
message when an invalid symbol follows a valid symbol. My
'error_found' and 'error_this_case' handles that, but it seems a
little convoluted. Is there a clearer way?

Symbol get_sym(void);
Symbol sym;

void stmt_seq(void) {
int error_found = 0;

for (;;) {
int error_this_case = 0;
switch (sym) {
case ident_sym : ident_stmt(); break;
case while_sym : while_stmt(); break;
case if_sym: if_stmt(); break;

case endwhile_sym:
case else_sym:
case eof_sym:
return;

default:
if (!error_found)
error("expecting stmt");
error_this_case = 1;
get_sym();
}
if (error_this_case)
error_found = 1;
else
error_found = 0;
}
}
 
P

Peter Pichler

Ed Davis said:
In the following code fragment, I only want to print an error
message when an invalid symbol follows a valid symbol. My
'error_found' and 'error_this_case' handles that, but it seems a
little convoluted. Is there a clearer way?

Read your own specification. If I get it right, you only need to know
that the previous symbol was valid. One flag. Simple.

This is not a C question BTW, it is about algorithms. Hence OT here.

Peter
 
M

Malcolm

Ed Davis said:
In the following code fragment, I only want to print an error
message when an invalid symbol follows a valid symbol.
What you want to do is write this function.

void handlerr(char *message)
{
static int flag = 0;
if(!flag)
printf("%s\n", message);
flag = 1;
}

and pass all your errors through it.
 
R

Richard Heathfield

Malcolm said:
What you want to do is write this function.

void handlerr(char *message)
{
static int flag = 0;
if(!flag)
printf("%s\n", message);
flag = 1;
}

and pass all your errors through it.

You might want to make that parameter const, so that the caller feels a
little more confident about passing (the address of the first character in)
a string literal to the function.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top