Charlie's Friday Pointer Workshop 26.08.16

Are you on the Unreal course, learning C++ or a C++ veteran? Do you want to apply your knowledge of pointers and test your understanding of the memory model? Then C.F.P.W. is for you. I’ll start off with an easy one…

Read the code and answer the questions without compiling it or running it.

#include <iostream>
#include <cstdint>

int32_t cfpw1(int32_t v)
{
    int32_t r;

    char* p = (char*)&v;
    char* q = (char*)&r;

    q[3] = p[0];
    q[2] = *(p + 1);
    *(q + 1) = p[2];
    *(q) = *(p + 3);

    return r;
}

int main()
{
    std::cout << cfpw1(0) << std::endl;
    std::cout << cfpw1(64) << std::endl;
    std::cout << cfpw1(cfpw1(1337)) << std::endl;

    return 0;
}
  1. What does cfpw1() do?
  2. This operation has a name and is used widely in computing. What is it called and where is it used?
  3. What does the program print to the standard output stream?
  4. What assumptions are made about the char type in this fragment? Are these the only assumptions made by the code?
  5. Name any system, architecture or circumstance under which these assumptions are false.

(If you can find a way to obscure your answers - perhaps in spoiler-tags if these forums support that feature - that would be best. I’ll check them and post scores out of 5. I’ll reveal the solution and the winner (first to the highest score, reward is kudos) before posting the next in the series… which will not necessarily be next Friday, depending on the weather in the Alps.)

Privacy & Terms