‹ BackHN Continuity

Thread

C++ Insights – See your source code with the eyes of a Compiler

172 points · 36 comments · rramadass

  1. StilesCrisis · · focus · HN ↗
    I wish the readme example showed a lambda capture. Now that's where compiler magic REALLY shows up.
    1. sltkr · · focus · HN ↗
      C++ lambdas are just structs that overload operator(); once you realize that they become a lot less mysterious. But it's a great example of how this tool is useful to learn about those things (of course you could also read the C++ standard but who has time for that?)

      Here&#x27;s an example: <a href="https:&#x2F;&#x2F;cppinsights.io&#x2F;s&#x2F;f04b6896" rel="nofollow">https:&#x2F;&#x2F;cppinsights.io&#x2F;s&#x2F;f04b6896

      (That also shows how C++&#x27;s range-based for-loops work, which is similarly some syntactic suger for a fairly mundane for-loop, but details are interesting: unlike a typical for-loop, the loop variable is declared inside the loop body.)

      1. Someone · · focus · HN ↗
        &gt; That also shows how C++&#x27;s range-based for-loops work, which is similarly some syntactic suger for a fairly mundane for-loop, but details are interesting: unlike a typical for-loop, the loop variable is declared inside the loop body

        That’s not true in C++, is it? There, this does not compile

          for(int i = 0; i &lt; 3; ++i)
          {}
          i = i + 1;
        
        (<a href="https:&#x2F;&#x2F;cppinsights.io&#x2F;s&#x2F;26405687" rel="nofollow">https:&#x2F;&#x2F;cppinsights.io&#x2F;s&#x2F;26405687: error: use of undeclared identifier &#x27;i&#x27;)

        <a href="https:&#x2F;&#x2F;en.cppreference.com&#x2F;cpp&#x2F;language&#x2F;for" rel="nofollow">https:&#x2F;&#x2F;en.cppreference.com&#x2F;cpp&#x2F;language&#x2F;for:

        “A for statement equivalent to:

          {
            init-statement
            while ( condition )
            {
              statement
              expression ;
            }
          }
        
        Except that […]”

        and

        “While in C names declared in the scope of init-statement and condition can be shadowed in the scope of statement, it is forbidden in C++:

          for (int i = 0;;)
          {
            long i = 1;   &#x2F;&#x2F; valid C, invalid C++
            &#x2F;&#x2F; ...
          }
        “
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.