[英]Evaluating boolean expression with recursive
I've wrote a program to recursively evaluate boolean expression.我编写了一个程序来递归评估 boolean 表达式。 But when I run with input
"(1|1)"
, in the second recursion of function S, specifically in line result = result || P()
但是当我使用输入
"(1|1)"
运行时,在 function S 的第二次递归中,特别是在result = result || P()
result = result || P()
instead of step into P()
, it passes the line and returns result. result = result || P()
而不是 step into P()
,它通过该行并返回结果。 However it works fine with input "(~1|1)"
.但是,它适用于输入
"(~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. result || P()
只要求其中一个值 - result
或P()
- 为 TRUE 以满足表达式。 If result
is TRUE when result || P()
如果
result
为 TRUE 当result || P()
result || P()
is evaluated the function is not required to be called - this is known as "short-circuit evaluation".评估
result || P()
不需要调用 function - 这称为“短路评估”。 Change your code to:将您的代码更改为:
bool p_val;
p_val = P();
result = result || p_val;
in order to ensure that the function is actually invoked.为了确保 function 被实际调用。
result = result || P();
P
will never will called if result
is the true
如果
result
为true
, P
将永远不会被调用
result = result && P();
P
will never will called if result
is false
如果
result
为false
, P
将永远不会被调用
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它被称为https://en.wikipedia.org/wiki/Short-circuit_evaluation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.