Should I use goto statement?
是否应该使用goto语句
goto语句也被称为无条件转移语句,它通常与条件语句配合使用来改变程序流向,使得程序转去执行语句标号所标识的语句。
关于是否应该使用goto语句,历史上也争论不休。恐怕国内大部分教授高级编程语言的课堂上,都会主张在结构化程序设计中不使用goto语句, 以免造成程序流程的混乱,使得理解和调试程序都产生困难。历史上支持goto语句有害的人的主要理由是:goto语句会使程序的静态结构和动态结构不一致,从而使程序难以理解且难以查错。并且G·加科皮尼和C·波姆从理论上证明了:任何程序都可以用顺序、分支和重复结构表示出来。这个结论表明,从高级程序语言中去掉goto语句并不影响高级程序语言的编程能力,而且编写的程序的结构更加清晰。
然而伟大的哲学家黑格尔说过:存在即合理。当笔者刚从校园中走出的时候,对于goto语句有害论也深以为然,然后多年之后在自己编写的代码中随处可见goto的身影。如今很多高级编程语言中,似乎是难以看见goto的身影:Java中不提供goto语句,虽然仍然保留goto为关键字,但不支持它的使用;C#中依然支持goto语句,但是一般不建议使用。其实可以很容易发现一点,这些不提倡使用goto语句的语言,大多是有自带的垃圾回收机制,也就是说不需要过多关心资源的释放的问题,因而在程序流程中没有“为资源释放设置统一出口”的需求。然而对于C++语言来说,程序员需要自己管理资源的分配和释放。倘若没有goto语句,那么我们在某个函数资源分配后的每个出错点需要释放资源并返回结果。虽然我们依然可以不使用goto语句完整地写完流程,但是代码将变得又臭又长。譬如我们需要写一个全局函数g_CreateListenSocket用来创建监听套接字,那么如果不使用goto语句,我们的代码将会是这个样子:
#include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #define MAX_ACCEPT_BACK_LOG 5 void g_CloseSocket(int &nSockfd) { if ( -1 == nSockfd ) { return; } struct linger li = { 1, 0 }; ::setsockopt(nSockfd, SOL_SOCKET, SO_LINGER, (const char *)&li, sizeof(li)); ::close(nSockfd); nSockfd = -1; } in_addr_t g_InetAddr(const char *cszIp) { in_addr_t uAddress = INADDR_ANY; if ( 0 != cszIp && '\0' != cszIp[0] ) { if ( INADDR_NONE == (uAddress = ::inet_addr(cszIp)) ) { uAddress = INADDR_ANY; } } return uAddress; } int g_CreateListenSocket(const char *cszIp, unsigned uPort) { int nOptVal = 1; int nRetCode = 0; int nSocketfd = -1; sockaddr_in saBindAddr; // create a tcp socket nSocketfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if ( -1 == nSocketfd ) { return nSocketfd; } // set address can be reused nRetCode = ::setsockopt(nSocketfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&nOptVal, sizeof(nOptVal)); if ( 0 != nRetCode ) { g_CloseSocket(nSocketfd); return nSocketfd; } // bind address saBindAddr.sin_family = AF_INET; saBindAddr.sin_addr.s_addr = g_InetAddr(cszIp); saBindAddr.sin_port = ::htons(uPort); nRetCode = ::bind(nSocketfd, (struct sockaddr *)&saBindAddr, sizeof(saBindAddr)); if ( 0 != nRetCode ) { g_CloseSocket(nSocketfd); return nSocketfd; } // create a listen socket nRetCode = ::listen(nSocketfd, MAX_ACCEPT_BACK_LOG); if ( 0 != nRetCode ) { g_CloseSocket(nSocketfd); return nSocketfd; } return nSocketfd; }
上面蓝色标记的代码中就包含了出错时候对资源(这里是套接字描述符)进行清理的操作,这里只有单一的资源,所以流程看起来也比较干净。倘若流程中还夹杂着内存分配、打开文件的操作,那么对资源释放操作将变得复杂,不仅代码变得臃肿难看,还不利于对流程的理解。而如果使用了goto语句,那么我们统一为资源释放设定单一出口,那么代码将会是下面这个样子:
int g_CreateListenSocket(const char *cszIp, unsigned uPort) { int nOptVal = 1; int nRetCode = 0; int nSocketfd = -1; sockaddr_in saBindAddr; // create a tcp socket nSocketfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if ( -1 == nSocketfd ) { goto Exit0; } // set address can be reused nRetCode = ::setsockopt(nSocketfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&nOptVal, sizeof(nOptVal)); if ( 0 != nRetCode ) { goto Exit0; } // bind address saBindAddr.sin_family = AF_INET; saBindAddr.sin_addr.s_addr = g_InetAddr(cszIp); saBindAddr.sin_port = ::htons(uPort); nRetCode = ::bind(nSocketfd, (struct sockaddr *)&saBindAddr, sizeof(saBindAddr)); if ( 0 != nRetCode ) { goto Exit0; } // create a listen socket nRetCode = ::listen(nSocketfd, MAX_ACCEPT_BACK_LOG); if ( 0 != nRetCode ) { goto Exit0; } // success here return nSocketfd; Exit0: // fail and clean up resources here if (-1 != nSocketfd) { g_CloseSocket(nSocketfd); } return nSocketfd; }
其实可以发现,加入goto语句之后,流程反而变得清晰了。一个函数将拥有两个出口:执行成功返回和执行失败返回。每次在流程某处出错后都跳转到固定标号处执行资源释放操作,这样在主体流程中将不再出现与资源释放相关的代码,那么主体流程只需专注于逻辑功能,代码将变得更易于理解和维护。另外一个好处就是不容易忘记释放资源,只需要养成分配完一个资源后立即在资源统一释放处编写资源释放代码的好习惯即可,对于程序员复查自己的代码也带来好处。
使用宏来简化代码量
仔细观察上面的代码,再结合前面所言的goto语句通常与条件语句配合使用来改变程序流向,可以总结规律:我们总是检查某个条件是否成立,如果条件不成立立即goto到指定的函数执行失败入口处,那么我们可以设计宏如下:
#undef DISABLE_WARNING #ifdef _MSC_VER // MS VC++ #define DISABLE_WARNING(code, expression) \ pragma(warning(push)) \ pragma(warning(disable:code)) expression \ pragma(warning(pop)) #else // GCC #define DISABLE_WARNING(code, expression) \ expression #endif // _MSC_VER #undef WHILE_FALSE_NO_WARNING #define WHILE_FALSE_NO_WARNING DISABLE_WARNING(4127, while(false)) #undef PROCESS_ERROR_Q #define PROCESS_ERROR_Q(condition) \ do \ { \ if (!(condition)) \ { \ goto Exit0; \ } \ } WHILE_FALSE_NO_WARNING #undef PROCESS_ERROR #define PROCESS_ERROR(condition) \ do \ { \ if (!(condition)) \ { \ assert(false); \ goto Exit0; \ } \ } WHILE_FALSE_NO_WARNING
int g_CreateListenSocket(const char *cszIp, unsigned uPort) { int nOptVal = 1; int nRetCode = 0; int nSocketfd = -1; sockaddr_in saBindAddr; // create a tcp socket nSocketfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP); PROCESS_ERROR(-1 != nSocketfd); // set address can be reused nRetCode = ::setsockopt(nSocketfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&nOptVal, sizeof(nOptVal)); PROCESS_ERROR(0 == nRetCode); // bind address saBindAddr.sin_family = AF_INET; saBindAddr.sin_addr.s_addr = g_InetAddr(cszIp); saBindAddr.sin_port = ::htons(uPort); nRetCode = ::bind(nSocketfd, (struct sockaddr *)&saBindAddr, sizeof(saBindAddr)); PROCESS_ERROR(0 == nRetCode); // create a listen socket nRetCode = ::listen(nSocketfd, MAX_ACCEPT_BACK_LOG); PROCESS_ERROR(0 == nRetCode); // success here return nSocketfd; Exit0: // fail and clean up resources here if (-1 != nSocketfd) { g_CloseSocket(nSocketfd); } return nSocketfd; }
统一函数出口
如果想统一函数出口,其实方法很简单:只需要加入一个int nResult字段,初始化为false,在函数流程完全走完时标记为true,然后在释放资源处判断该字段是否为false即可。可以参考下面代码:
int g_CreateListenSocket(const char *cszIp, unsigned uPort) { int nResult = false; int nRetCode = false; int nOptVal = 1; int nSocketfd = -1; sockaddr_in saBindAddr; // create a tcp socket nSocketfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP); PROCESS_ERROR(-1 != nSocketfd); // set address can be reused nRetCode = ::setsockopt(nSocketfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&nOptVal, sizeof(nOptVal)); PROCESS_ERROR(0 == nRetCode); // bind address saBindAddr.sin_family = AF_INET; saBindAddr.sin_addr.s_addr = g_InetAddr(cszIp); saBindAddr.sin_port = ::htons(uPort); nRetCode = ::bind(nSocketfd, (struct sockaddr *)&saBindAddr, sizeof(saBindAddr)); PROCESS_ERROR(0 == nRetCode); // create a listen socket nRetCode = ::listen(nSocketfd, MAX_ACCEPT_BACK_LOG); PROCESS_ERROR(0 == nRetCode); // success here nResult = true; Exit0: // fail and clean up resources here if (!nResult) { if (-1 != nSocketfd) { g_CloseSocket(nSocketfd); } } return nSocketfd; }
测试代码
最后附上上述代码的测试代码:
int main(int argc, char ** argv) { socklen_t nAddrLen = sizeof(struct sockaddr_in); int nListenSocketfd = -1; struct sockaddr_in saRemoteAddr; nListenSocketfd = g_CreateListenSocket("", 9999); if ( -1 == nListenSocketfd ) { return 0; } while (true) { ::memset(&saRemoteAddr, 0, sizeof(saRemoteAddr)); int nSocketfd = ::accept(nListenSocketfd, (struct sockaddr *)&saRemoteAddr, &nAddrLen); ::printf("Accept a new connection from [ip - %s, port - %d]\n", ::inet_ntoa(saRemoteAddr.sin_addr), ::ntohs(saRemoteAddr.sin_port) ); g_CloseSocket(nSocketfd); } return 1; }
The above is the detailed content of Should I use goto statement?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.

Get started easily: How to use pip mirror source With the popularity of Python around the world, pip has become a standard tool for Python package management. However, a common problem that many developers face when using pip to install packages is slowness. This is because by default, pip downloads packages from Python official sources or other external sources, and these sources may be located on overseas servers, resulting in slow download speeds. In order to improve download speed, we can use pip mirror source. What is a pip mirror source? To put it simply, just
