系统程序设计学习笔记
来源:互联网 发布:mac怎么打开多个终端 编辑:程序博客网 时间:2024/04/30 21:59
今天主要看了作用域和传值传引用以及递归,都是十分典型的问题,而且我发现卡耐基上面讲的很不错,所以做一下笔记。
首先是作用域,这里有一个典型的程序:
#include <stdio.h>int first;int second;void callee ( int first ){ int second; second = 1; first = 2; printf("callee: first = %d second = %d\n", first, second);}int main (int argc, char *argv[]){ first = 1; second = 2; callee(first); printf("caller: first = %d second = %d\n", first, second); return 0;}
从这里面我明白局部作用域的优先级高于全局作用域。还有就是程序在调用函数之前会对参数做一个复制(如果是传值的话),那么这个局部对象怎么才能观察到呢?还没解决。
另外就是传值和传引用。
#include <stdio.h>int first;int second;void callee ( int * first ){ int second; second = 1; *first = 2; printf("callee: first = %d second = %d\n", *first, second);}int main (int argc, char *argv[]){ first = 1; second = 2; callee(&first); printf("caller: first = %d second = %d\n", first, second); return 0;}这个程序只是传指针,其实还是传值,因为指针的值是通过传值传进去的。其实传引用只是改变了一下形势,传指针和传引用是等价的。
标准的传值
void fun(int a);
标准的传引用
void fun(int& a);
#include <stdio.h>#include <stdlib.h>void callee (int n){ if (n == 0) return; printf("%d (0x%08x)\n", n, &n); callee (n - 1); printf("%d (0x%08x)\n", n, &n);}int main (int argc, char * argv[]){ int n; if (argc < 2) { printf("USAGE: %s <integer>\n", argv[0]); return 1; } n = atoi(argv[1]); callee(n); return 0;}下面这段话讲的很好:
What happens is that the compiler inserts additional code for every function call and every function return. This code allocates any local variables that the callee needs for that invocation. Multiple invocations of the callee activate this allocation code over and over again. This is called dynamic allocation, because the local variables are allocated at runtime, as needed.
Global variables can be allocated statically. This means that the compiler can fix specific addresses for global variables before the program executes. But because functions can be called recursively, and each recursive invocation needs its own instantiation of local variables, compilers must allocate local variables dynamically. Such dynamic behavior makes the program run more slowly, so it is not desirable. But it is necessary for local variables.
意思就是每次函数调用之前编译器会做一些事情,做什么事情呢?就是插入一些额外的代码。这些代码会为函数分配局部变量。由于程序不知道有多少局部变量,所以全局变量的地址和局部变量的地址相差的很大。
- 系统程序设计学习笔记
- Linux 程序设计学习笔记----文件管理系统
- 数据库程序设计 学习笔记
- 计算机学习笔记--程序设计
- 计算机学习笔记--程序设计
- 《C++程序设计》学习笔记
- 《LUA程序设计》学习笔记
- LINUX程序设计--学习笔记
- linux程序设计--学习笔记
- linux程序设计学习笔记
- C++程序设计学习笔记
- Windows程序设计学习笔记
- 系统级程序设计笔记(零)
- 《Windows程序设计》学习笔记(1)
- windows程序设计第一章学习笔记
- VC WINDOWS 程序设计学习笔记
- WIN32多线程程序设计学习笔记
- 《程序设计入门经典》学习笔记
- 图像处理(二)直方图均衡化
- 日历时间加减法
- Hibernate分页查询
- MOS管开关电路设计知识
- 二叉树遍历:递归方法与非递归方法——递归程序修改为非递归的方法
- 系统程序设计学习笔记
- UbuntuServer搭建Git服务器之SSH基本用法(一)
- 移动mysql数据文件目录(datadir)以及selinux的一些经验
- Android adb shell command
- Windows7/Windows Server 2008 右键"选择默认程序"出错解决方案
- hdu 2242 考研路茫茫――空调教室(Tarjan+树型DP)
- 最大子序列、最长递增子序列、最长公共子串、最长公共子序列、字符串编辑距离
- 安装MYSQL之转移数据目录的成功经验
- AGAL是什么