1.下面的表达式是否合法?如果合法,它执行了什么任务?
3 * x * x - 4 * x + 6;
解析:
计算这个表达式的值,然后就将其丢弃。
它是合法的,但不会影响程序的状态。这些操作都不具有副作用,并且它们的计算结果并没有赋值给任何变量。
#include <stdio.h>
#include <stdlib.h>
int main( void ){
int x = 3;
3 * x * x - 4 * x + 6;
printf( "x = %d, the value of 3 * x * x - 4 * x + 6 is %d\n", x, 3 * x * x - 4 * x + 6 );
return EXIT_SUCCESS;
}
输出:
2.赋值语句的语法是怎样的?
解析:
说明符 变量 = 表达式; //初始化语句方式
或者说明符 变量; 变量 = 表达式; //赋值语句的语法
#include <stdio.h>
#include <stdlib.h>
int main( void ){
int y;
printf( "original y = %d\n", y );
int x = 3; //初始化语句的语法
y = 2; //赋值语句的语法
printf( "after assignment operation, x = %d, y = %d\n", x, y );
return EXIT_SUCCESS;
}
输出:
3.用下面这种方法使用代码是否合法?如果合法,你是否曾经想过这样使用?
...
statement
{
statement
statement
}
statement
解析:
如果是变量的定义,这样前两句statement能够通过编译,后面都是非法的。如果不是变量,例如进行赋值操作是合法的。
#include <stdio.h>
#include <stdlib.h>
int main( void ){
const static int a = 2;
{
const static int a = 2;
const static int b = 2;
}
const static int b = 2;
const static int c = 2;
{
const static int c = 2;
/*
** can't pass compilation:
** because of [Error] redeclaration of 'const int c'
** and [Note] 'const int c' previously declared here
** const static int c = 2;
*/
}
/*
** can't pass compilation:
** because of [Error] redeclaration of 'const int c'
** and [Note] 'const int c' previously declared here
** const static int c = 2;
*/
int d = 2;
d = 3;
{
d = 3;
d = 3;
}
d = 3;
printf( "a = %d, b = %d, c = %d, d = %d\n", a, b, c, d );
return EXIT_SUCCESS;
}
输出:
4.当编写if语句时,如果在then子句中没有语句,但在else子句中有语句,该如何编写?还能改用其他形式来达到同样的目的码?
译注:C并没有then关键字,这里所说的then子句就是紧跟if表达式后面的语句;相当于其他语言的then子句部分。
解析:
使用空语句:
if( condition ){
;
}else{
statements
}
可以对条件进行修改,省略空的then子句。它们的效果是一样的:
if( !condition ){
statements
}
#include <stdio.h>
#include <stdlib.h>
int main( void ){
int condition;
condition = 0;