Simulating Booleans in Bison with C

2019-07-28 10:52发布

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?

2条回答
做自己的国王
2楼-- · 2019-07-28 10:56

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-07-28 11:02

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.

查看更多
登录 后发表回答