C++ Semantics and GPU Memory Trade-offs: Four Short Answers
System DesignModel answerLast 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::coutprints - 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).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Enums and structs
enum Level { Low, Mid = 10, High }; // 0, 10, 11
enum class Mode : unsigned char { Off, On }; // 0, 1
struct Rec { char flag; Level lvl; double score; int count = 3; };
Rec r{'x', High}; // score and count omitted
Enumerator values. The first enumerator is 0 and each later one is the previous plus 1. An explicit value resets the sequence, so High is 11.
Scoped vs. unscoped.
- Unscoped enumerators leak into the surrounding scope and convert implicitly to integers, so
std::cout << r.lvlprints11, never the name. enum classkeeps names scoped (Mode::On) and does not convert implicitly. Printing needsstatic_cast<int>(...)or a customoperator<<; the plain stream expression will not compile.- The underlying type of an
enum classdefaults toint. For an unscoped enum it is implementation-defined unless you fix it.
Aggregate initialization. Braces fill members in declaration order. Omitted members use their default member initializer if present (count becomes 3), otherwise they are value-initialized, which means zero for scalars (score becomes 0.0). This differs from a plain local Rec x;, where members without initializers are indeterminate and reading them is undefined behavior. Static and global objects are zero-initialized first. With C++20 designated initializers, the designators must follow declaration order.
Printing traps. char, signed char and unsigned char print as characters, so an 8-bit enum or integer type may show a glyph instead of a number (use +x or a cast). bool prints 1 or 0 unless std::boolalpha is set.
Values vs. layout. Padding exists so each member sits at an address satisfying its alignment. In Rec, flag is at offset 0, lvl at 4, score at 8, count at 16, and tail padding rounds the size up to a multiple of 8, giving sizeof(Rec) == 24 (typical ABI) rather than 17. Padding changes offsets and sizeof, never member values. Ordering members largest-first often helps: {char a; double b; char c;} is 24 bytes, while {double b; char a; char c;} is 16. Padding bytes are unspecified, so comparing structs with memcmp is unreliable.
2. Macro vs. function
#define SQ(x) x * x
#define MAX(a, b) ((a) > (b) ? (a) : (b))
inline int sq(int x) { return x * x; }
SQ(n + 1); // n + 1 * n + 1 -> precedence bug
MAX(i++, j); // i++ can run twice
sq(n + 1); // argument evaluated once
| Aspect | Macro | Function / inline / constexpr |
|---|---|---|
| Processing | Text substitution before compilation | Parsed and type-checked by the compiler |
| Type safety | None; errors surface at the expansion | Full checking, overloads, templates |
| Argument evaluation | Once per textual use (0, 1 or many times) | Exactly once |
| Scope | Ignores namespaces | Respects scope |
| Debugging | Usually invisible, confusing errors | Breakpoints, symbols, stepping |
| Performance | No call overhead | Optimizers inline small functions, so usually the same |
inline today mostly relaxes the One Definition Rule so definitions can live in headers; actual inlining is the optimizer's call. Use constexpr for compile-time evaluation. Macros remain appropriate for include guards, conditional compilation, stringification and token pasting, and capturing __FILE__ / __LINE__ in logging or assertions.
3. GPU matrix addition
Matrix addition is memory-bandwidth-bound. Each output needs one add, two loads and one store: about 12 bytes of traffic for one FLOP in float. There is no data reuse, so speed is determined by how close you get to peak DRAM bandwidth.
__global__ void add(const float* __restrict__ a, const float* __restrict__ b,
float* __restrict__ c, int n) {
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n;
i += gridDim.x * blockDim.x)
c[i] = a[i] + b[i];
}
- Uncoalesced access is the real slow case: if threads in a warp stride across rows of a row-major array, each warp touches many cache lines and wastes most of every transaction.
- Simple coalesced kernel (consecutive threads touch consecutive addresses, flattened 1-D indexing) already runs close to peak bandwidth.
- Vectorized loads (
float4,vload4) issue fewer instructions for the same bytes. The gain is modest (often single-digit to low-teens percent) and needs 16-byte alignment plus tail handling when the element count is not divisible by 4. - Shared-memory staging does not help: each element is used once, so staging only adds copies, a
__syncthreads()and occupancy pressure. It pays off when data is reused (tiled matmul, stencils, transposes).
Verdict: a coalesced, flattened kernel with enough blocks to saturate memory, optionally vectorized. The larger win is usually fusing the add with adjacent operations to avoid extra DRAM round trips, which also saves power on mobile GPUs where memory traffic dominates energy.
4. Uniform operations and repeated read-only values
Goal: stop redoing identical work per thread, and stop fetching the same bytes repeatedly.
- Hoist and precompute. If a result does not depend on the thread index, compute it on the host, or once per block (one thread writes it to shared memory, then
__syncthreads()), or as a kernel argument. Avoid recomputing it in every thread. - Use broadcast-friendly memory. Small read-only values belong in kernel arguments, CUDA
__constant__memory, or OpenCL__constant, which broadcast one value to a whole warp or wavefront in a single transaction. For larger read-only data, useconst __restrict__or__ldgso the read-only cache is used. - Keep it in registers. Load once into a local variable and reuse it inside loops rather than rereading global memory. Use a warp shuffle to share a value from one lane across the warp.
- Specialize. If the value is known at compile time, use templates or
constexprso the compiler folds it away, and so uniform branches disappear. Uniform branches do not diverge, but removing them still saves instructions. - Why it saves power. Fewer DRAM transactions and fewer redundant ALU operations reduce energy directly; memory accesses cost far more energy than arithmetic.
Common mistakes: assuming shared memory always helps; ignoring alignment and the tail in vectorized code; using memcmp on padded structs; printing 8-bit values and expecting numbers; and putting large or divergent-access data into constant memory, where it serializes reads instead of broadcasting them.