Simulating Booleans in Bison with C

孤街醉人 提交于 2019-12-13 02:16:16

问题


I am trying to make a logic calculator using C and bison, but I'm having trouble because C does not have a boolean type.

This is part of my Flex rules:

"TRUE" |
"T"    |
"t"  {yylval = 1; return TRUE; }

"FALSE" |
"F"    |
"f"  {yylval = 0; return TRUE; }

This is part of my Bison rules:

line:
        EOL
        | exp EOL {printf("%d %d %d \n"), $1, $2,$$;}
        ;

exp: TRUE
   | FALSE
   ;

This is the output when I type T followed by EOL (end of line) in my calculator:

10 12 1

10 is ascii for newline, 12 is ascii for carriage return and 1 is Ascii for start I have the same output for F.

How can I make it so 1 is in $1 if I enter a T and 0 is in $1 if I enter a F?


回答1:


I'm no Bison expert and it's been a long time since I've used it, so I suggest that you read the Flex manual because I think your Flex is wrong. Your rules need to return a token type, not TRUE. In your Bison you have a FALSE token type, but no rule that returns that type. What you want is

exp: BOOLEAN

in Bison, and Flex rules that return BOOLEAN, not TRUE, for the boolean strings. You will also want

%token BOOLEAN

%%

at the beginning of your Bison file.

Take a look at the links on the right side of this page which show other people's questions about flex and bison.

Your comment "I'm having trouble because C does not have a boolean type" is incorrect and has misled people into giving you irrelevant advice about C's types.




回答2:


C does have bool as of the C99 standard. You can use the header #include <stdbool.h> and then use Boolean types in the following manner:

bool love = true;
if(love){
    //...
}

So, just like a standard bool.



来源:https://stackoverflow.com/questions/12593750/simulating-booleans-in-bison-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!