# 《码出高效》学习笔记与书中错误记录

if (true) int x;
for (; ; ) int y;
while (true) int z;

Every declaration that introduces a name has a scope, in which they can be used.

C，不管是 ANSI C 还是 C99，都无法通过编译，直接给出 Error。

error: expected expression before ‘int’

warning: unused variable ‘x’ [-Wunused-variable]

C++。

public class Main {
public static void main(String args[]) {
if (true) int jxtxzzw;
}
}

Unresolved compilation problem: Syntax error on token “)”, Statement expected after this token at …

Declaration not allowed here

Java 的理由容易找：

Every declaration that introduces a name has a scope, in which they can be used.

int x 是一个声明，Declaration。

int x = 10; 是一个定义，Definition。

{int x;} 或者 {int x = 10;} 由于有了 {}，是一条语句，Statement。

I guess the counter-intuitive part of the question is: if this is correct C:
if (a == 1) {  int b = 10;}
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?
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.

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf 以及
https://www.quora.com/What-does-error-expected-expression-before-int-mean-in-C

0 评论