KatInterview

C++ Semantics and GPU Memory Trade-offs: Four Short Answers

System DesignModel answer

Last updated

Answer four fundamentals questions: enum and struct behavior in C++, macros versus inline functions, GPU matrix-add kernel design, and optimizing uniform or repeated read-only values.

Answer the four short questions below as you would in a technical discussion. For each one, state the rule, give a brief example, and name the common pitfall.

1. Enums and structs in C++. You are given a program that declares an enum and a struct containing an enum member, initializes the struct with a brace list that leaves out some trailing members, and prints the result. Explain how you would work out its output. Cover:

  • default enumerator values and what happens after an explicit value
  • scoped (enum class) versus unscoped enums
  • aggregate initialization and what happens to omitted initializers
  • implicit conversions that affect what std::cout prints
  • why a member's value is a separate matter from the struct's memory layout and padding

2. Macro versus function. Compare a function-like preprocessor macro with a regular or inline function. Discuss when each is processed, type safety, side effects, argument evaluation, debuggability and performance.

3. GPU matrix addition. You must add two large matrices on a GPU. Compare a straightforward kernel (each thread reads one element from each input in global memory and writes one result) with variants that use coalesced access, vectorized loads, or shared-memory staging. Which is usually best, and why?

4. Uniform work and repeated read-only values. Every thread in a kernel either performs the same computation or repeatedly reads the same read-only value. How would you improve speed and power efficiency?

Hints

Hint 1

For part 1, trace the code in three steps: assign values to the enumerators, apply the initializer list member by member in declaration order, then ask what type each printed expression has. Compute offsets separately for sizeof.

Hint 2

For part 3, count bytes moved per arithmetic operation. If every element is touched exactly once, ask what could shared memory possibly reuse.

Hint 3

For part 4, separate two ideas: avoiding repeated computation (do it once, hoist it) and avoiding repeated fetches (put the value in a memory space or register that broadcasts cheaply).