7 C Control Statements: Branching and Jumps

8 The goto Statement

The goto statement, bulwark of the older versions of BASIC and FORTRAN, is available in C. However, C, unlike those two languages, can get along quite well without it. Kernighan and Ritchie refer to the goto statement as “infinitely abusive” and suggest that it “be used sparingly, if at all.” First, we will show you how to use goto. Then, we will show why you usually
don’t need to.

The goto statement has two parts—the goto and a label name. The label is named following the same convention used in naming a variable, as in this example:

goto part2;

For the preceding statement to work, the function must contain another statement bearing the part2 label. This is done by beginning a statement with the label name followed by a colon:

part2: printf(“Refined analysis:\n”);

8.1 Avoiding goto

In principle, you never need to use the goto statement in a C program, but if you have a
background in older versions of FORTRAN or BASIC, both of which require its use, you might have developed programming habits that depend on using goto. To help you get over that dependence, we will outline some familiar goto situations and then show you a more C-like approach:

Handling an if situation that requires more than one statement:

if (size > 12)
 	goto a;
goto b;
a: cost = cost * 1.05;
flag = 2;
b: bill = cost * flag; 

In old-style BASIC and FORTRAN, only the single statement immediately following the if condition is attached to the if. No provision is made for blocks or compound statements. We have translated that pattern into the equivalent C. The standard C approach of using a compound statement or block is much easier to follow:

if (size > 12){
    cost = cost * 1.05;
    flag = 2;
}
bill = cost * flag; 

Choosing from two alternatives:

if (ibex > 14)
    goto a;
sheds = 2;
goto b;
a: sheds= 3;
b: help = 2 * sheds;

Having the if else structure available allows C to express this choice more cleanly:

if (ibex > 14)
    sheds = 3;
else
    sheds = 2;
help = 2 * sheds; 

Indeed, newer versions of BASIC and FORTRAN have incorporated else into their syntax.

Setting up an indefinite loop:

readin: scanf("%d", &score);
if (score < O)
    goto stage2;
lots of statements
goto readin;
stage2: more stuff; 

Use a while loop instead: 
 scanf("%d", &score);
 while (score <= 0)
 {
 lots of statements
 scanf("%d", &score);
 }
 more stuff; 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值