Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

6.5.2 表达式

下面首先编写expression(),它的文法规则如下:

由于这是我们第一次尝试将一组文法规则转换为代码,将会经历一些不成功的开始。这是学习一种新技术常见的过程,我们可以从中学到很多有用的东西。特别地,通过观察相似代码段表现出令人吃惊的不同行为,初学者可以学到很多。阅读代码是积累编程技巧的有效途径。

6.5.2.1 表达式:第一次尝试

首先看一下Expression'+'Term规则,我们首先调用expression(),然后寻找+(和-),最后是调用term():

这个程序看起来不错。它几乎是文法的一个简单誊写,其结构确实非常简单:首先读入一个Expression,然后判断它后面是否跟着一个‘+’或者一个‘-’,如果确是这样,则再读取Term。

不幸的是,这里存在很大问题。怎样才能知道一个表达式的结尾在何处,以便于寻找一个‘+’或者一个‘-’呢?请记住:我们的程序从左到右读取输入,它不能预取符号来查看前面是否有‘+’运算符。事实上,这个expression()函数只能执行到第一行代码,因为expression()在一直不停地调用自己,这种情况称为无限递归(infinite recursion)。实际上递归调用还是会停止的,因为每次调用都会消耗一定内存空间,当计算机内存被耗光时,程序就会退出。“递归”的含义就是程序调用自身,并不是所有的递归都是无限的,递归是一种非常有用的程序设计技术(参见8.5.8节)。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252