第8章 专家的迷惑
欢迎阅读本书中最难理解的一部分。这一章为数不多的几个程序的设计目的是,哪怕您是最专业的C和C++程序员,也可能要被它所困惑。可能您自认为了解所有的编程技术,但是接着我们所陈述的几个问题是所有这些编程过程中可能遇到问题中最困难的。
本章只有三个问题。如果您能解决一个,您就可以认为您是专家级的程序员了。如果能解决两个,将会令我非常吃惊。如果能把这里的三个问题全都解决,您就可认为您是最好的程序员了。
8.1 程序97:再现Hello
下面这段程序会打印出什么?
1 /************************************************
2 * Normally I would put in a comment explaining ? *
3 * what this program is nominally used for. ? *
4 * But in this case I can figure out no ? *
5 * practical use for this program. ? *
6 ************************************************/
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <stdlib.h>
10
11 int main()
12 {
13 printf("Hello ");
14 fork();
15 printf("\n");
16 exit(0);
17 }
(请参见“提示214”和“答案50”)
花絮
莎士比亚已经给过我们一个古老的问题:to be or not to be?计算机科学给了我们这个答案:FF。
0X2B | ~0X2B=0XFF
(编者按:英文中to be和2B的发音类似。)
后记:
在大部分情况下,当我把这个笑话讲述给一个非技术人员听时,他们都只是奇怪地看着我。技术人员专注地想了大约一分钟,然后说:“您是对的。”在大约一百人中,只有一个人是真正地笑了。
8.2 程序98:控制调试器
这个程序员有个非常聪明的想法。他想在语句:
if(debugging)
中放一些代码,然后运行这个程序。当他想调试程序的时候,用交互式的调试器debugger来改变debugging的值(0或1)。但是这段代码的实际运行却大出他的意外。
1 /************************************************
2 * Code fragment to demonstrate how to use the ? *
3 * debugger to turn on debugging. All you ? *
4 * have to do is put a breakpoint on the "if"
? *
5 * line and change the debugging variable. ? *
6 ************************************************/
7 extern void dump_variables(void);
8
9 void do_work()
10 {
11 static int debugging = 0;
12
13 if (debugging)
14 {
15 dump_variables();
16 }
17 // Do real work
18 }
(请参见“提示174”和“答案84”)
花絮
在UNIX操作系统下创建文件是很容易的事情。因此,用户习惯创建很多文件,因而也占用了大量的磁盘空间。关于UNIX系统有这样的一个说法,如果在UNIX系统中只有一件事是很标准的,那就是UNIX系统不断地弹出让用户清理文件的消息框。
—— 源自早期的《UNIX管理员指南》
8.3 程序99:幻影文件
目录中没有一个叫delete.me的文件。为什么这个程序一直让我们删除它呢?
1 /************************************************
2 * delete_check -- Check to see if the file ? *
3 * delete.me exists and tell the user ? *
4 * to delete it if it does. ? *
5 ************************************************/
6 #include <iostream>
7 #include <unistd.h>
8 #include <cstdio>
9
10 int main()
11 {
12 // Test for the existence of the file
13 if (access("delete.me", F_OK)) {
14 bool remove = true;
15 }
16 if (remove) {
17 std::cout <<
18 "Please remove 'delete.me'\n";
19 }
20 return (0);
21 }
(请参见“提示98”和“答案35”)
|