C/C++ goto 语句

注:以下代码仅用于学习交流,请勿用于商业用途
Authors:
[email protected]

  • 01 "声明狼藉"的goto 语句
  • 02 goto 语句 使用的集中场景
01 "声明狼藉"的goto 语句

goto语句的经常被贬斥为一种糟糕的编程方式,大学课程c语言课程中讲师这样称道,教科书很少见到goto语句的考题,甚至工程实践中也少见此类源码

有限的使用goto语句,可以提高代码的执行效率(但是可能会造成代码结构不易理解,比如回跳)
goto语句可以简化嵌套循环或者if else的复杂结构,从而使代码执行过程更加简洁

02 goto 语句 使用的几种场景

情景1 嵌套循环:简化代码结构,便于阅读
输出:val = 4704 i = 48 j = 98

#include <iostream>
int main()
{
	using namespace std;
	long val (0);
	int i = 0;
	int j = 0;
	for(i = 1;i < 1000;i++)
	{
		for(j = 1;j < 100;j++)
		{
			val= i* j;
			if(val > 4700)
			goto bottom;
		}
	}
	bottom:
		cout << "val = " << val << " i = " << i << " j = " << j <<endl; 
	return 0;
}

情景2 频繁使用return语句:简化代码结构
借用一位同行的代码,原始链接如下:
https://bbs.csdn.net/topics/380068160

int getresult_use_goto()
{
    int iResult = 0;
 
    FILE*    fp1 = NULL;
    FILE*    fp2 = NULL;
    char*    pMem1 = NULL;
    char*    pMem2 = NULL;
     
    fp1 = fopen("C:\\file1", "rb");
    if (NULL == fp1)  goto End;
 
    fp2 = fopen("C:\\file2", "rb");
    if (NULL == fp2)  goto End;
 
    pMem1 = (char *)malloc(1000);
    if (NULL == pMem1) goto End;
 
    pMem2 = (char *)malloc(2000);
    if (NULL == pMem2) goto End;
 
    iResult = 1;
 
End:
    if (fp1) fclose(fp1);
    if (fp2) fclose(fp2);
    if (pMem1) free(pMem1);
    if (pMem2) free(pMem2);
    return iResult;
}

情景3 优化程序执行效率
在linux内核代码中有非常多的这种使用范例(回跳),一个基本的使用思想是加强代码执行效率

static int sync_buffers(dev_t dev, int wait)
{
	int i, retry, pass = 0, err = 0;
	struct buffer_head * bh;

	/* One pass for no-wait, three for wait:
	   0) write out all dirty, unlocked buffers;
	   1) write out all dirty buffers, waiting if locked;
	   2) wait for completion by waiting for all buffers to unlock.
	 */
repeat:
	retry = 0;
	bh = free_list;
	for (i = nr_buffers*2 ; i-- > 0 ; bh = bh->b_next_free) {
		if (dev && bh->b_dev != dev)
			continue;
#ifdef 0 /* Disable bad-block debugging code */
		if (bh->b_req && !bh->b_lock &&
		    !bh->b_dirt && !bh->b_uptodate)
			printk ("Warning (IO error) - orphaned block %08x on %04x\n",
				bh->b_blocknr, bh->b_dev);
#endif
		if (bh->b_lock)
		{
			/* Buffer is locked; skip it unless wait is
			   requested AND pass > 0. */
			if (!wait || !pass) {
				retry = 1;
				continue;
			}
			wait_on_buffer (bh);
		}
		/* If an unlocked buffer is not uptodate, there has been 
		   an IO error. Skip it. */
		if (wait && bh->b_req && !bh->b_lock &&
		    !bh->b_dirt && !bh->b_uptodate)
		{
			err = 1;
			continue;
		}
		/* Don't write clean buffers.  Don't write ANY buffers
		   on the third pass. */
		if (!bh->b_dirt || pass>=2)
			continue;
		bh->b_count++;
		ll_rw_block(WRITE, 1, &bh);
		bh->b_count--;
		retry = 1;
	}
	/* If we are waiting for the sync to succeed, and if any dirty
	   blocks were written, then repeat; on the second pass, only
	   wait for buffers being written (do not pass to write any
	   more buffers on the second pass). */
	if (wait && retry && ++pass<=2)
		goto repeat;
	return err;
}

你可能感兴趣的:(UNIX/LINUX,C)