V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
smallghost
V2EX  ›  程序员

看看这两个宏定义有啥区别

  •  
  •   smallghost · Oct 20, 2013 · 3790 views
    This topic created in 4585 days ago, the information mentioned may be changed or developed.
    #define SAFE_RELEASE_NULL(p) do { if(p) { (p)->release(); (p) = 0; } } while(0)

    上面这个宏定义和下面的有区别吗?
    #define SAFE_RELEASE_NULL(p) if(p) { (p)->release(); (p) = 0; }
    6 replies    1970-01-01 08:00:00 +08:00
    loggerhead
        1
    loggerhead  
       Oct 20, 2013   ❤️ 1
    有.
    比如:
    if (1)
    SAFE_RELEASE_NULL(arg);
    else
    doSomeThing();

    后者末尾加分号就错了
    xpfd
        2
    xpfd  
       Oct 20, 2013
    @loggerhead 正解,能不用宏的地方尽量不要用,尽量使用inline和enmu代替
    iEverX
        3
    iEverX  
       Oct 20, 2013
    @loggerhead 所说确实是一个方面

    最重要应该是,while(0)把一个语句块包起来,整个宏就就类似于一个语句一样。

    #define A(arg) dosth(arg);doanother(arg)
    #define B(arg) do { dosth(arg);doanother(arg); } while(0)

    if (xxx) A(arg); // 这一行和下一行,doanother(arg)的执行有区别
    if (xxx) B(arg);
    yangxin0
        4
    yangxin0  
       Oct 20, 2013
    jokerlee
        5
    jokerlee  
       Oct 20, 2013
    do while{...}用在宏里还有一个作用是{}之间是一个独立的作用域,里面定义的变量不会污染外部作用域
    xgdyhaiyang
        6
    xgdyhaiyang  
       Oct 22, 2013
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3011 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 07:20 · PVG 15:20 · LAX 00:20 · JFK 03:20
    ♥ Do have faith in what you're doing.