‹ BackHN Continuity

Thread

Type Punning in C and C++

36 points · 23 comments · ingve

  1. LelouBil · · focus · HN ↗
    I don't understand the example in "Why C and C++ Differ".

    Shouldn't the code return 3 in the base case and 4 if the check for 2 was assumed to always hold ?

    1. bena · · focus · HN ↗
      You're halfway there. It's a little more messed up than that.

      IIRC, this is all little-endian. So assume our 8 bytes labeled A-H. For a 32 bit/4 byte integer, they will be read as DCBA. For a 64 bit/8 byte integer, HGFEDCBA.

      So the struct is set up like a = DBCA, b = HGFE. So when we assign 2 and 3 to a and b, it should look like this in memory:

      00000010 00000000 00000000 00000000 and 00000011 00000000 00000000 00000000

      When we cast that to a uint64 and assign 4 to it, we should wind up with:

      00000100 00000000 00000000 00000000 00000000 00000000 00000000 00000000

      Which effectively zeros out b.

      So if the conditional is evaluated, it will evaluate to false, we return b, which is 0.

      If the conditional is not evaluated, we should return the value in a, which is 4.

      1. LelouBil · · focus · HN ↗
        Oooh thanks, I missed that the cast was into a 64 bit integer
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.