Will the Compiler Optimize this out

后端 未结 7 1360
悲&欢浪女
悲&欢浪女 2020-12-09 11:27

Say I have something like this in a C Code. I know you can use a #define instead, to make the compiler not compile it, but just out of curiosity I\'m asking if

7条回答
  •  一向
    一向 (楼主)
    2020-12-09 11:57

    Below is specific to C language. I don't know how Java handles it.

    Since int is defined as a const, if (i) becomes a no-op instruction here. A smart compiler should be able to optimize away that empty if statement.

    Example: VC 2008

    A non-empty {} with if statement:

    const int i = 1;
    // mov dword ptr [i], 1
    if (i)
    // mov eax, 1
    // test eax, eax
    // je wmain+35h
    {
       int j = 2;
       // move dword ptr [j], 2
    }
    // ..
    

    Empty {} with if statement:

    const int i = 1;
    // mov dword ptr [i], 1
    if (i)
    {
    }
    // ..
    

提交回复
热议问题