关于“声明”的一句话我在Stephen Prita的C Primer Plus中无法理解

时间:2016-07-28 10:17:13

标签: c

有一句关于“声明”的句子,我在Stephen Prita的C Primer Plus中无法理解。

在第5章中,有一节解释了陈述和表达之间的区别。作者解释声明如下:

  

语句

     

语句是程序的主要构建块。程序是一系列带有一些必要标点符号的陈述。声明是   完整的计算机说明。在C中,表示了陈述   最后用分号。因此,

     

legs = 4   只是一个表达式(可能是更大表达式的一部分),但是 legs = 4;

     

是一个声明。

然后作者给出了一个例子:

  

虽然声明(或者至少是合理的声明)是完整的指令,但并非所有完整的指令都是声明。   请考虑以下声明:

     

x = 6 + (y = 5);

     

其中,子表达式y = 5是一个完整的指令,但它只是语句的一部分。因为完整的指令不是   必须是一个声明,需要一个分号来识别   真正是陈述的说明。

作者说“y = 5”是一个完整的指令,但正如她上面提到的那不仅仅是一个表达,而不是一个完整的陈述?

1 个答案:

答案 0 :(得分:0)

每个C程序都包含语句。程序逐语句执行。反过来,每个陈述通常包含一些表达。表达式还可以包括子表达式。例如:

/* diff_statements.c */
#include <stdio.h>
#define SIZE 10        /* SIZE symbolic constant */ 

int main(void)
{
    int index, sum;    /* declaration statement */
    int boys[SIZE];    /* array declaration */

    printf("user enter no of boys in 10 classes...\n");
    /* function statement */

    for (index = 0; index < SIZE; index++) 
        scanf("%d", &boys[index]);

    /* for statement with single statement */ 

    /* IT'S A GOOD PRACTICE TO REVIEW IF U ENTERED CORRECT VALUES */

    printf("No. of boys you entered for 10 classes are as:\n");
    for (index = 0; index < SIZE; index++)
        printf("%d\t", boys[index]);
    printf("\n");

    printf("Summing up & Displaying boys in all classes...\n");

    /* for statement with block of statements */     
    for (index = 0; index < SIZE; index++) {
        sum += boys[index];
        ;   /* Null Statement; this does nothing here */
    }

    printf("Total boys in %d classes is %d\n", SIZE, sum);
    return 0;
}

每个C语句都以分号';'结尾。虽然表达式没有。例如:

x + y;    /* x + y is an exp but x + y; is a statement. */
5 + 7;    /* similarly as above */

while (5 < 10) {  
    /* 5 < 10 is a relational exp, not a statement. */
    /* used as a while test condition */

    /* other statements in while loop */
}

result = (float) (x * y) / (u + v); 
okey = (x * y) / (u + w) * (z = a + b + c + d);

/* (z = a + b + c + d) is a sub-expression in the above */
/* expression. */

表达式是人类逻辑中的完整指令,但不是根据C语言。从C的角度来看,完整的指令是一个Statement,它是以分号结尾的表达式的有效组合。