gpt4 book ai didi

c - 在 lex 的定义和规则部分中编写语句之间的区别

转载 作者:行者123 更新时间:2023-11-30 16:12:07 25 4
gpt4 key购买 nike

我是 lex 的新手。假设目标是编写一个 lex 程序来计算单词数。我们应该声明一个 int 变量 counter 并在每次看到单词时递增它。问题是这些代码示例之间有什么区别:

%option main
%{
#include<stdio.h>
#include<string.h>
int i = 0;
%}

%%
([a-zA-Z0-9])+ {i++;}
%%

%option main
%{
#include<stdio.h>
#include<string.h>
%}
%%
int i = 0;
([a-zA-Z0-9])+ {i++;}
%%

%option main
#include<stdio.h>
#include<string.h>
int i = 0;
%%
([a-zA-Z0-9])+ {i++;}
%%

#include<stdio.h> #include<string.h> 的地方影响这里的代码吗?程序是否会根据我们声明整数变量i的位置而改变?

最佳答案

是的,顺序很重要。但这不是 #include这是这里的问题。

这是编写该程序的一种正确方法:

%option main
/* The %{ and %} delimiters must be at the beginning of the line.
Lines between %{ and %} are copied verbatim into the generated
file, near to the beginning.
*/
%{
#include <stdio.h>
#include <string.h>
%}
%%
/* These lines must be indented. Indented lines after the %% and
* before the first rule are inserted verbatim into the generated
* lexer right at the beginning of the definition of the function
* yylex. This lets you declare local variables, like nwords.
*/
int nwords = 0;
([a-zA-Z0-9])+ { ++nwords; }
/* Other rules go here. Every possible input should be matched by
* some rule.
*/

/* At a minimum, you can ignore all unmatched characters
* using the following fall back (which should be the last rule).
*/
.|\n ;

<<EOF>> { printf("%d words found.\n", nwords);
return 0; /* Let the caller know we're done */
}

<<EOF>>这里需要规则来打印出单词数,因为 nwordsyylex 之外将不可用。另一种方法是制作 nwords全局变量,但全局变量通常被认为是一个坏主意。 (无论如何,您正在使用 %option main ,这意味着您不会编写 main() 函数,因此没有其他逻辑位置来报告字数。

如果你想制作nwords全局的,你可以声明 nwords%{...%} block ,以便在任何函数之外声明它。

Flex 让您可以省略 %{%}只要要插入的代码是缩进的。但这非常脆弱,会让许多阅读你的代码的人感到困惑;绝对建议您使用分隔符,这样您就不必担心插入的代码是否缩进。

关于c - 在 lex 的定义和规则部分中编写语句之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58408369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com