I've wrote a program to recursively evaluate boolean expression. But when I run with input "(1|1)"
, in the second recursion of function S, specifically in line result = result || P()
result = result || P()
instead of step into P()
, it passes the line and returns result. However it works fine with input "(~1|1)"
. How can I fix this?
#include <stdbool.h>
#include <stdlib.h>
char *s;
char *f;
bool P(), A();
// The grammar is:
// S -> P||S | P&&S | P
// P -> A | ~A
// A -> (S) | 0 | 1
bool S() {
bool result = P();
if (*s == '|') {
s++;
result = result || P();
}
else
if (*s == '&') {
s++;
result = result && P();
}
return result;
}
bool P() {
if (*s == '~') {
s++;
return !A();
}
else
{
return A();
}
}
bool A() {
bool result;
if (*s == '(') {
s++;
result = S();
if (*s == ')') s++;
else {
printf("Syntaktisch falsch! Stelle %ld, Art: Anzahl von '(' und ')' sind nicht gleich\n", s-f);
exit(1);
}
}
else
if (*s == '1') {
s++;
result = true;
}
else
if (*s == '0') {
s++;
result = false;
}
else {
printf("Syntaktisch falsch! Stelle: %ld, Art: Boolscher Ausdruck fehlt\n", s-f); // Hier gibt Fehlermeldung aus, wenn Input String ist nur '~'.
exit(1);
}
return result;
}
int main(int argc, char *argv[])
{
bool result;
if (argc != 2) exit(1);
s = argv[1];
f = s;
result = S();
printf("%d\n", result);
return 0;
}
result || P()
result || P()
only requires that ONE of the values - result
OR P()
- be TRUE in order to satisfy the expression. If result
is TRUE when result || P()
result || P()
is evaluated the function is not required to be called - this is known as "short-circuit evaluation". Change your code to:
bool p_val;
p_val = P();
result = result || p_val;
in order to ensure that the function is actually invoked.
result = result || P();
P
will never will called if result
is the true
result = result && P();
P
will never will called if result
is false
so place the call first to make sure it is called.
P() || result
P() && result
it is called https://en.wikipedia.org/wiki/Short-circuit_evaluation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.