对于上面的声明,请告诉哪一个是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 ;-)
更多推荐
发布评论