C 错误:int 之前的预期表达式 [英] C error: Expected expression before int

查看:22
本文介绍了C 错误:int 之前的预期表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试以下代码时,我得到了提到的错误.

When I tried the following code I get the error mentioned.

if(a==1)
  int b =10;

但以下在语法上是正确的

But the following is syntactically correct

if(a==1)
{
   int b = 10;
}

这是为什么?

推荐答案

这其实是一个相当有趣的问题.它并不像最初看起来那么简单.作为参考,我将以 N1570

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

我猜这个问题的反直觉部分是:如果这是正确的 C:

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

那么为什么这不是正确的 C 呢?

then why is this not also correct C?

if (a == 1)
  int b = 10;

我的意思是,单行条件 if 语句不管有没有大括号都应该没问题,对吧?

I mean, a one-line conditional if statement should be fine either with or without braces, right?

答案在于 C 标准定义的 if 语句的语法.我在下面引用的语法的相关部分.简而言之:int b = 10 行是声明,而不是语句,以及if 的语法语句需要在它正在测试的条件之后的语句.但是如果你把声明用大括号括起来,它就变成了一个声明,一切都很好.

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

只是为了完整地回答这个问题——这与范围无关.存在于该范围内的 b 变量将无法从其外部访问,但程序在语法上仍然是正确的.严格来说,编译器不应该对其抛出错误.当然,无论如何,您都应该使用 -Wall -Werror 进行构建;-)

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)


(6.7) declaration:
            declaration-specifiers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

这篇关于C 错误:int 之前的预期表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆