相关疑难解决方法(0)

为什么在宏中使用明显无意义的do-while和if-else语句?

在许多C/C++宏中,我看到宏的代码包含在看似无意义的do while循环中.这是一些例子.

#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
Run Code Online (Sandbox Code Playgroud)

我看不出它do while在做什么.为什么不在没有它的情况下写这个?

#define FOO(X) f(X); g(X)
Run Code Online (Sandbox Code Playgroud)

c c++ c++-faq c-preprocessor

758
推荐指数
8
解决办法
9万
查看次数

C:嵌套的Ifs或Gotos

管理C程序资源的最佳方法是什么?我应该使用嵌套的if结构还是应该使用goto语句?

我知道有很多的忌讳有关的goto语句.但是,我认为当地资源清理是合理的.我提供了两个样品.一个比较嵌套的if结构,另一个使用goto语句.我个人发现goto语句使代码更容易阅读.对于那些可能认为嵌套if提示更好的结构的人来说,想象一下如果数据类型不是char*,就像Windows句柄一样.我觉得嵌套的if结构会随着一系列CreateFile函数或任何其他需要大量参数的函数而失控.

文章表明,本地goto语句创建C代码RAII.代码很简洁易于理解.想象一下,作为一系列嵌套的if语句.

我知道goto在许多其他语言中都是禁忌,因为它们存在其他控制机制,如try/catch等,但是,在C中似乎是合适的.

#include <stdlib.h>

#define STRING_MAX 10

void gotoExample()
{
    char *string1, *string2, *string3, *string4, *string5;

    if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string1;
    if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string2;
    if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string3;
    if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string4;
    if ( !(string5 = …
Run Code Online (Sandbox Code Playgroud)

c if-statement goto

9
推荐指数
4
解决办法
3481
查看次数

标签 统计

c ×2

c++ ×1

c++-faq ×1

c-preprocessor ×1

goto ×1

if-statement ×1