习题41
学习static定义静态变量的用法。
实现思路: 用static声明和未用static声明变量进行对比,即可得出static的作用。
代码如下:
#include <stdio.h>
int main(){
void func();
int i;
for(i = 0;i < 10; i++){
func();
}
return 0;
}
void func(){
int i = 0;
static int num = 0;
printf("In func:i = %d, num = %d\n", i, num);
i++;
num++;
}
打印:
In func:i = 0, num = 0
In func:i = 0, num = 1
In func:i = 0, num = 2
In func:i = 0, num = 3
In func:i = 0, num = 4
In func:i = 0, num = 5
In func:i = 0, num = 6
In func:i = 0, num = 7
In func:i = 0, num = 8
In func:i = 0, num = 9
习题42
学习使用定义自动变量的用法。
实现思路: 自动变量用auto关键字声明,函数中的形参和在函数中定义的变量(包括在复合语句中定义的变量)都属于自动变量,默认不用关键字修饰即为自动变量,可进行对比分析。
代码如下:
#include <stdio.h>
int main(){
int i, m = 0, n = 0;
for(i = 0;i < 10; i++){
printf("In main: m = %d, n = %d. ", m, n);
{
auto int n = 10;
printf("In block: m = %d, n = %d\n", m, n);
}
m++;
n++;
}
return 0;
}
打印:
In main: m = 0, n = 0. In block: m = 0, n = 10
In main: m = 1, n = 1. In block: m = 1, n = 10
In main: m = 2, n = 2. In block: m = 2, n = 10
In main: m = 3, n = 3. In block: m = 3, n = 10
In main: m = 4, n = 4. In block: m = 4, n = 10
In main: m = 5, n = 5. In block: m = 5, n = 10
In main: m = 6, n = 6. In block: m = 6, n = 10
In main: m = 7, n = 7. In block: m = 7, n = 10
In main: m = 8, n = 8. In block: m = 8, n = 10
In main: m = 9, n = 9. In block: m = 9, n = 10
习题43
学习使用static的另一用法。
实现思路: static在单独的代码块中也可以实现在一次函数执行结束后变量未被销毁、保留当前的值,下次调用函数时即使用保留在内存中的变量值,直到运行期间结束才释放该变量。
代码如下:
#include <stdio.h>
int main(){
int i, m = 0, n = 0;
for(i = 0;i < 10; i++){
printf("In main: m = %d, n = %d. ", m, n);
{
static int n = 10;
printf("In block: m = %d, n = %d\n", m, n);
n--;
}
m++;
n++;
}
return 0;
}
打印:
In main: m = 0, n = 0. In block: m = 0, n = 10
In main: m = 1, n = 1. In block: m = 1, n = 9
In main: m = 2, n = 2. In block: m = 2, n = 8
In main: m = 3, n = 3. In block: m = 3, n = 7
In main: m = 4, n = 4. In block: m = 4, n = 6
In main: m = 5, n = 5. In block: m = 5, n = 5
In main: m = 6, n = 6. In block: m = 6, n = 4
In main: m = 7, n = 7. In block: m = 7, n = 3
In main: m = 8, n = 8. In block: m = 8, n = 2
In main: m = 9, n = 9. In block: m = 9, n = 1
习题44
学习使用external的用法。
实现思路: 用extern来声明外部变量,以扩展外部变量的作用城,从变量的定义处开始,到本程序文件的末尾。
代码如下:
#include <stdio.h>
int main(){
int max(int a, int b);
extern A, B;
printf("Max = %d\n", max(A, B));
return 0;
}
int max(int a, int b){
return a > b ? a : b;
}
int A = 12, B = 20;
习题45
学习使用register定义变量的方法。
实现思路: C语言允许将局部变量的值放在CPU中的寄存器中,需要用时直接从寄存器取出参加运算,不必再到内存中去存取,从而提高执行效率,这种变量叫做寄存器变量,用关键字register声明。
代码如下:
#include <stdio.h>
int main(){
long fact(int n);
int i;
for(i = 1; i <= 10; i++){
printf("%2d! = %d\n", i, fact(i));
}
return 0;
}
long fact(int n){
register long f = 1;
int i;
for(i = 1; i <= n; i++){
f *= i;
}
return f;
}
打印:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
本文原文首发来自博客专栏C语言实战,由本人转发至https://www.helloworld.net/p/gyDha3hzOF2P,其他平台均属侵权,可点击https://blog.csdn.net/CUFEECR/article/details/106824367查看原文,也可点击https://blog.csdn.net/CUFEECR浏览更多优质原创内容。