C的误差:INT之前的预期前pression [英] C error: Expected expression before int

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

问题描述

当我尝试以下code我得到的错误提及。

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;

我的意思是,一个单行的条件如果语句应该罚款无论有或没有括号,对吧?

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

问题就出在如果语句的语法,由C标准定义。语法中的相关部分,我下面引用。简洁:在 INT B = 10 行是的声明的,不是的语句的,而对于语法如果语句要求有条件的,它是经过测试的声明。但是,如果你括在大括号声明,就成了一个声明,一切都很好。

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之前的预期前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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