📄 ch01s03.html
字号:
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>3. CPS与goto</title><link rel="stylesheet" href="html.css" type="text/css"><meta name="generator" content="DocBook XSL Stylesheets V1.69.1"><link rel="start" href="index.html" title="Java网络程序员看Continuation"><link rel="up" href="ch01.html" title="Chapter 1. CPS与网络程序流程控制"><link rel="prev" href="ch01s02.html" title="2. CPS猜数字游戏"><link rel="next" href="ch01s04.html" title="4. CPS与网络流程控制"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">3. CPS与goto</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="ch01s02.html">Prev</a> </td><th width="60%" align="center">Chapter 1. CPS与网络程序流程控制</th><td width="20%" align="right"> <a accesskey="n" href="ch01s04.html">Next</a></td></tr></table><hr></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d0e96"></a>3. CPS与goto</h2></div></div></div><p>如果您觉得上面的这段代码难以理解,那么我们来看看这个游戏的第三种写法,也许您就会恍然大悟。下面这段代码使用label和goto写成的。</p><pre class="programlisting">#include <stdio.h>#include <stdlib.h>void main() { int ans; int guess; ans = random() % 100 + 1; goto prompt; prompt: printf("Guess a number [1, 100]: "); goto guess; guess: scanf("%d", &guess); if (guess < ans) { printf("Number too small.\n"); goto prompt; } else if (guess > ans) { printf("Number too big.\n"); goto prompt; } else { printf("Congratulations!"); goto finishgame; } finishgame: /* do nothing */}</pre><p>把这段用goto写成的代码与上面的CPS比较一下,您会发现两者惊人地相似,几乎是一一对应的关系。CPS模式中的每个函数其实就是一个label,函数print事实上就是printf后面加一个goto,而我们在上面的例子里实际做的,就是把while结构用goto重新写了一遍!</p><p>需要注意的是:一般情况下CPS比goto的功能更强大,只在我们的CPS函数print接受的continuation的数据类型为 void (*continuation)(void)时我们才能把CPS简单地转换为goto。正因为此,有人将continuation称为带参数的goto。</p></div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="ch01s02.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="ch01.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="ch01s04.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">2. CPS猜数字游戏 </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 4. CPS与网络流程控制</td></tr></table></div></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -