词法和语法错误的区别(Difference between lexical and syntax error)

编程入门 行业动态 更新时间:2024-10-25 18:23:38
词法和语法错误的区别(Difference between lexical and syntax error) int 2ab; int 2;

对于上面的声明,请告诉哪一个是C语言中的词法错误和语法错误。 我对这两个声明都感到困惑。

int 2ab; int 2;

For above declarations, please tell which one is a lexical error and a syntax error in the C language. I am confused in both the declarations.

最满意答案

这两个声明都是无效的,所以你有理由困惑,但出于不同的原因:

如果编译器不能将字符序列识别为适当的词法标记,则会发生词法错误。 2ab不是有效的C令牌。 (请注意, 2ab是一个有效的C预处理令牌,可用于令牌粘贴宏,但这似乎超出了您当前的技能水平)。

当一个标记序列与C构造不匹配时会发生语法错误:语句,表达式,预处理指令... int 2; 是一种语法错误,因为类型在这样的上下文中启动一个定义并且数字不是一个预期的标记:一个标识符或可能是一个* ,一个( ,一个说明符或一个限定符是预期的。

请注意,限定符和类型或存储说明符在C声明中几乎可以以任何顺序出现:

int typedef const long cint; // same as typedef const long int cint; int volatile static short x; // same as static volatile short int x; int long unsigned long extern ll; // same as extern unsigned long long int ll;

上面的有效声明是你不应该使用的变体的例子;-)

Both declarations are invalid, so you are rightfully confused, but for different reasons:

A lexical error occurs when the compiler does not recognize a sequence of characters as a proper lexical token. 2ab is not a valid C token. (Note that 2ab is a valid C preprocessing token that can be used in token pasting macros, but this seems beyond your current skill level).

A syntax error occurs when a sequence of tokens does not match a C construction: statement, expression, preprocessing directive... int 2; is a syntax error because a type starts a definition and a number is not an expected token in such a context: an identifier or possibly a *, a (, a specifier or a qualifier is expected.

Note that qualifiers and type or storage specifiers can appear in pretty much any order in C declarations:

int typedef const long cint; // same as typedef const long int cint; int volatile static short x; // same as static volatile short int x; int long unsigned long extern ll; // same as extern unsigned long long int ll;

The above valid declarations are examples of variations you should not use ;-)

更多推荐

本文发布于:2023-08-04 00:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词法   区别   语法错误   Difference   syntax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!