gcc complex constant folding

前端 未结 4 1837
失恋的感觉
失恋的感觉 2021-01-12 03:10

It seems that gcc has some limitation on complex constant folding. Here is an example:

static inline unsigned int DJBHash(const char *str)
{
   int i;
   uns         


        
4条回答
  •  醉酒成梦
    2021-01-12 04:08

    The OP is interested in constant-folding in C, but just for its C++ sibling: in C++14, you can simply put constexpr in front of both functions, and modify the loop to to compensate for strlen() not being constexpr

    #include
    
    static inline constexpr unsigned int DJBHash(const char *str)
    {
       unsigned int hash = 5381;
    
       for(auto i = 0; i < 512; ++i) {
          if (*str == '\0') return hash;
          hash = ((hash << 5) + hash) + static_cast(*str);   
       }
    
       return hash;
    }
    
    constexpr unsigned int f(void)
    {   
        return DJBHash("01234567890123456");
    }
    
    int main()
    {
        constexpr auto h = f(); 
        std::cout << std::hex << h << "\n"; // 88a7b505
    }
    

    Live Example using Clang 3.4 SVN with -std=c++1y.

    NOTE: the current Clang implementation does not properly run with a while(*str != '\0'). Instead, a finite loop of 512 with a return condition inside does the job.

提交回复
热议问题