C++ Language Semantics and GPU Kernel Trade-offs

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Address the following four C++ and GPU systems engineering questions:

  1. Reasoning about enum and struct programs: Walk through how you determine the printed output and memory footprint of a C++ snippet that combines enum types with struct objects. Cover automatic enumerator value assignment, unscoped enum versus scoped enum class, brace-based aggregate initialization, members left out of an initializer list, implicit conversions and integral promotions during stream output, and why logical field values differ from physical struct layout, alignment, and padding.
  2. Preprocessor #define macros versus C++ / inline functions: Contrast function-like preprocessor macros with ordinary or inline C++ functions across translation stage (text preprocessing versus compilation), static type checking, expression side effects and repeated argument evaluation, source-level debuggability, and runtime speed.
  3. GPU matrix-addition kernel strategies: For computing $C = A + B$ on a GPU, compare a straightforward one-element-per-thread kernel (reading two inputs from global DRAM and writing one sum) against variants focused on memory access behavior—such as warp-coalesced indexing, vectorized wide loads, or staging tiles through on-chip shared memory. Identify which strategy is typically optimal for elementwise matrix addition and explain why.
  4. Removing redundant thread-uniform GPU work: When every thread in a GPU launch evaluates an identical scalar formula or repeatedly loads the same read-only parameter, how should you restructure the computation and memory placement to improve both execution speed and power consumption?

Scope & Expectations

  • Trace exact C++ rules for enumerator numbering, scope and implicit casts, value-initialized versus uninitialized struct members, std::cout character/integer formatting traps, and ABI alignment padding.
  • Demonstrate concrete failure modes of text-paste macros (precedence bugs and multi-evaluation side effects) alongside how optimizing compilers handle inline and constexpr functions.
  • Quantify arithmetic intensity for elementwise matrix addition to justify when coalescing, vectorized loads, shared-memory tiling, or kernel fusion help—and when shared memory adds pure overhead.
  • Connect host precomputation, register hoisting, and warp-broadcast constant memory to both throughput and the steep energy gap between off-chip DRAM fetches and on-chip arithmetic.

Step-by-step walkthrough

  1. Trace enum values and how C++ prints them

    Note: the sandbox on this platform runs Python, so this guide walks through each part in clear prose with self-contained C++ and CUDA examples. Sizes, offsets, and outputs assume a standard 64-bit platform (x86-64 or ARM64 with GCC or Clang) using C++14 or newer.

    When an interviewer asks what a C++ snippet mixing enum and struct prints, trace it in two separate steps: first work out each variable's numeric value, and second check the exact C++ type reaching std::cout <<, because operator<< formats characters, booleans, and integers differently.

    1. Enumerator numbering. Inside any enum, the first name defaults to 0 if you do not give it a value, and every later name without an explicit value equals previous + 1. So in enum Color { Red, Green = 5, Blue };, Red is 0, Green is 5, and Blue is 6.

    2. Unscoped enum vs scoped enum class. - An unscoped enum (enum Color) drops its names (Red, Green, Blue) straight into the surrounding scope, so two unscoped enums in the same namespace cannot both define Red. It also implicitly converts to an integer or bool: std::cout << Blue prints 6, Blue + 1 evaluates to 7, and bool ok = Blue; becomes true. (Going the other way still requires an explicit cast: Color c = 5; is a compile error.) - A scoped enum (enum class Mode) keeps its names inside Mode:: (Mode::On) and blocks implicit conversions. Writing std::cout << Mode::On or int x = Mode::On; fails to compile; you must cast explicitly with static_cast<int>(Mode::On). - Underlying integer type: enum class uses int (4 bytes) unless you specify another integer type such as : std::uint8_t (1 byte). An unscoped enum without : Type lets the compiler pick an integer type wide enough to hold its values (typically 4 bytes on 64-bit compilers).

    3. Printing traps with operator<< and integral promotion. - On mainstream platforms, std::uint8_t is a type alias (typedef) for unsigned char. Because std::cout << treats unsigned char as a text character, std::cout << static_cast<std::uint8_t>(Mode::On) when On = 65 prints the ASCII letter A, not 65! Cast to int whenever you want the numeric value. - Integral promotion is C++'s rule that arithmetic operators (+, -, *) automatically widen integer types narrower than int (such as char or uint8_t) to int before computing. So char c = 'A'; prints A on its own, whereas c + 1 has type int and prints 66. - A bool prints 1 or 0 by default unless std::boolalpha is enabled on the stream (true / false).

    #include <cstdint>
    #include <iostream>
    
    enum Color { Red, Green = 5, Blue };               // Red = 0, Green = 5, Blue = 6
    enum class Mode : std::uint8_t { Off, On = 65 };   // scoped, 1-byte underlying type
    
    int main() {
        std::cout << Red << ' ' << Green << ' ' << Blue << '\n';     // prints: 0 5 6
        std::cout << static_cast<int>(Mode::On) << '\n';              // prints: 65
        std::cout << static_cast<std::uint8_t>(Mode::On) << '\n';     // prints: A  (uint8_t is unsigned char!)
        bool flag = Blue;
        std::cout << flag << ' ' << std::boolalpha << flag << '\n';   // prints: 1 true
        char c = 'A';
        std::cout << c << ' ' << (c + 1) << '\n';                     // prints: A 66 (c + 1 promotes to int)
        // std::cout << Mode::On;  // compile error: enum class does not implicitly convert to int
    }
    
  2. Aggregate initialization and omitted fields in structs

    An aggregate is a plain struct (or array) with only public non-static data members, no user-declared constructors, and no virtual functions, allowing callers to initialize its members directly in declaration order using curly braces {} (since C++14, aggregates may also have default member initializers like int retries = 3;).

    When a struct is initialized, every member's value depends on whether braces were used and where the variable lives:

    +------------------------------+----------------------------+-----------------------------------------------+
    | Declaration                  | Explicitly listed members  | Omitted members                               |
    +------------------------------+----------------------------+-----------------------------------------------+
    | T x{a, b};                   | set to a, b in field order | default member initializer, else zeroed (0)   |
    | T x{};                       | (none listed)              | default member initializer, else zeroed (0)   |
    | T x;  (local / stack scope)  | (none listed)              | default member initializer, else GARBAGE (UB) |
    | static T x; or global T x;   | (none listed)              | zeroed at startup, then default initializers  |
    +------------------------------+----------------------------+-----------------------------------------------+
    

    Two subtle rules often come up in interviews: 1. Zeroing an omitted enum: Value initialization (the {} rule applied to omitted fields) sets numbers to 0, pointers to nullptr, and enums to static_cast<EnumType>(0) — even if the enum never defined an enumerator equal to 0! 2. No narrowing inside braces: Curly braces reject narrowing conversions (conversions that can lose information, such as double to int). Pixel q{'x', 7.5}; fails to compile, whereas int v = 7.5; compiles and truncates 7.5 to 7.

    struct Pixel {
        char tag;
        int value;
        Color color;
        Mode mode;
    };
    
    struct Config {
        int retries = 3;   // default member initializer
        double scale;      // no default initializer
        Color color;       // no default initializer
    };
    
    void demo() {          // inside a function (automatic / stack storage)
        Pixel p{'x', 7};   // tag='x', value=7, color=Red (0), mode=Mode::Off (0)
        Config a{};        // retries=3, scale=0.0, color=Red (0)
        Config b{5};       // retries=5, scale=0.0, color=Red (0)
        Config c;          // retries=3; scale and color hold indeterminate stack bytes (reading is UB!)
    }
    

    If we print every member of p, a, and b (casting p.mode to int), we get x 7 0 0, 3 0 0, and 5 0 0. By contrast, reading c.scale or c.color is undefined behavior (UB) (code whose result the C++ standard places no requirements on, allowing garbage outputs or optimizer surprises).

  3. Member values vs memory layout, alignment, and padding

    Printed member values tell you nothing about sizeof(Pixel). CPUs read memory fastest when each N-byte primitive sits at an address divisible by N — a hardware rule called alignment. To keep every field aligned, the compiler inserts unused filler bytes called padding between fields and at the end of the struct.

    On standard 64-bit platforms (char = 1 byte, int = 4 bytes, Color = 4 bytes, Mode = 1 byte), compare Pixel against the exact same fields sorted from largest alignment to smallest:

    struct Pixel { char tag; int value; Color color; Mode mode; };
    
    Byte offset:
      [ 0 ]          tag     (1 byte, align 1)
      [ 1 .. 3 ]     padding (3 unused bytes so `value` starts at a multiple of 4)
      [ 4 .. 7 ]     value   (4 bytes, align 4)
      [ 8 .. 11 ]    color   (4 bytes, align 4)
      [ 12 ]         mode    (1 byte, align 1)
      [ 13 .. 15 ]   padding (3 tail bytes so sizeof(Pixel) is a multiple of alignof(Pixel) = 4)
    Total: sizeof(Pixel) = 16 bytes (only 10 bytes hold actual data!)
    
    struct PixelCompact { int value; Color color; char tag; Mode mode; };
    
    Byte offset:
      [ 0 .. 3 ]     value   (4 bytes)
      [ 4 .. 7 ]     color   (4 bytes)
      [ 8 ]          tag     (1 byte)
      [ 9 ]          mode    (1 byte)
      [ 10 .. 11 ]   padding (2 tail bytes to reach multiple of 4)
    Total: sizeof(PixelCompact) = 12 bytes (saves 25% RAM and cache space!)
    

    Why does the compiler add tail padding at offsets 13..15? Imagine an array Pixel arr[2]. arr[1] sits immediately at byte offset sizeof(Pixel). Without those 3 tail bytes, arr[0] would be 13 bytes long, placing arr[1].value at byte 13 + 4 = 17 — an unaligned address!

    Two practical takeaways: - Order fields from largest alignment to smallest when defining hot data structures: for 1,000,000 pixels, PixelCompact takes 12 MB instead of 16 MB, saving 4 MB of cache and memory bandwidth for free. - Never compare or hash structs with memcmp: padding bytes contain unspecified leftover memory, so two Pixel objects with identical member values can differ in their padding bytes and fail memcmp(&p1, &p2, sizeof(Pixel)) == 0. Always compare field by field (or use bool operator==(const Pixel&) const = default; in C++20).

  4. Preprocessor macros vs functions and inline functions

    A preprocessor macro (#define) runs before the C++ compiler parses syntax or types: it performs blind find-and-replace text substitution. An ordinary, inline, or constexpr function is compiled as a real typed C++ entity. Almost every bug with function-like macros comes from blind text pasting:

    • Operator precedence bugs: #define SQUARE_BAD(x) x * x expands SQUARE_BAD(1 + 2) into 1 + 2 * 1 + 2, which evaluates to 5 instead of 9! Even #define SQUARE_HALF(x) (x) * (x) fails on 12 / SQUARE_HALF(2), expanding to 12 / (2) * (2) = 12 instead of 3. Every parameter and the entire macro body need parentheses: ((x) * (x)).
    • Multiple evaluation and side effects: Because a macro pastes its argument text everywhere the parameter appears, MAX(i++, j) expands to ((i++) > (j) ? (i++) : (j)). Starting from i = 5, j = 3, the condition checks 5 > 3 (i becomes 6), and then the true branch runs i++ a second time, returning 6 and leaving i == 7! Worse, SQUARE(i++) expands to ((i++) * (i++)), modifying i twice without sequencing — undefined behavior. A C++ function evaluates each argument exactly once before entering the body: max_of(i++, j) returns 5 and leaves i == 6.
    • Type safety and scope: Macros ignore types (MAX(2, 3.5) silently mixes int and double) and ignore namespaces (defining #define max ... in a header breaks std::max everywhere below it). Function templates enforce consistent types and obey namespaces.
    • Debuggability: The compiler and debugger never see the macro name — compiler errors point at expanded lines, and you cannot set a breakpoint inside a macro or see it in a stack trace.
    • Performance: With optimization enabled (-O2), compilers inline small functions automatically, emitting the exact same machine instructions as a macro with zero call overhead. In modern C++, the inline keyword primarily satisfies the One Definition Rule (ODR) (allowing an identical function definition to appear in a header included by multiple .cpp files without linker duplicate-symbol errors), while constexpr additionally lets the compiler evaluate calls like square(4) at compile time.
    #define SQUARE_BAD(x) x * x
    #define SQUARE(x) ((x) * (x))
    #define MAX(a, b) ((a) > (b) ? (a) : (b))
    
    constexpr int square(int x) { return x * x; }
    
    template <typename T>
    constexpr T max_of(T a, T b) { return a > b ? a : b; }
    
    // Precedence:  SQUARE_BAD(1 + 2) -> 5,     square(1 + 2) -> 9
    //              12 / ((2) * (2))  -> 3,     12 / square(2) -> 3
    // Side effect: int i = 5, j = 3;  MAX(i++, j)    returns 6 and leaves i == 7
    //              int i = 5, j = 3;  max_of(i++, j) returns 5 and leaves i == 6
    

    Keep macros only for jobs the language itself cannot express: conditional compilation (#ifdef), stringizing an expression (#expr in custom assertions), or token pasting (a##b).

  5. Prove GPU matrix addition is memory-bandwidth bound

    Before comparing GPU kernels for C = A + B, always check arithmetic intensity — the number of floating-point operations (FLOP) performed for every byte transferred between the GPU chip and off-chip DRAM. Take two 4096 * 4096 matrices of 32-bit float (4 bytes each):

    Total elements:       4096 * 4096 = 16,777,216 floats (~16.8 million)
    Off-chip DRAM bytes:  read A (4 B) + read B (4 B) + write C (4 B) = 12 bytes per element
                          12 B * 16,777,216 = 201,326,592 bytes (~201.3 MB)
    Math operations:      1 addition per element = 16.8 million FLOP
    Arithmetic intensity: 1 FLOP / 12 bytes = 0.083 FLOP/byte
    
    Data-center GPU example (1 TB/s DRAM bandwidth, 10 TFLOP/s compute):
      Minimum memory time:  201.3 MB / (1,000 GB/s) = 0.20 ms
      Minimum math time:    16.8 MFLOP / (10 TFLOP/s) = 0.0017 ms  (over 100x faster!)
    
    Mobile SoC GPU example (60 GB/s LPDDR bandwidth):
      Minimum memory time:  201.3 MB / (60 GB/s) = 3.36 ms
    

    Because moving the bytes takes roughly 100 times longer than adding the numbers, matrix addition is severely memory-bandwidth bound on every modern GPU. Tweaking the + instruction saves nothing; kernel speed is decided almost entirely by what fraction of peak DRAM bandwidth your memory access pattern achieves.

  6. Compare GPU kernels: coalescing, vectorized loads, and shared memory

    GPUs execute threads in lockstep groups called warps (32 threads on NVIDIA GPUs; called wavefronts or fiber groups on other GPUs). When all 32 threads in a warp request adjacent memory addresses at the same instant, hardware combines their 32 requests into minimal wide DRAM burst transfers — an optimization called memory coalescing.

    1. Simple one-thread-per-element kernel (coalesced vs strided). A 2-D matrix in C++ is stored row-by-row (row * cols + col). Inside a 2-D thread block, threadIdx.x varies fastest across threads 0..31 of a warp:

    Row-major memory:  [ row 0: col 0, col 1, ..., col 31, ... ] [ row 1: col 0, col 1, ... ]
    
    Coalesced mapping (col uses threadIdx.x):
      Warp threads tx=0..31 read a[row * cols + 0..31] -> 32 adjacent floats (128 contiguous bytes)
      Hardware fetches four 32-byte DRAM sectors -> 128 B fetched, 128 B used (100% efficiency!)
    
    Strided bug (row uses threadIdx.x):
      Warp threads tx=0..31 read a[0*cols + col], a[1*cols + col], ..., jumping by cols*4 bytes!
      Hardware touches 32 separate 32-byte DRAM sectors -> 1,024 B fetched for 128 B used (up to 8x waste!)
    
    // GOOD: threadIdx.x steps across columns -> 32 warp threads read 128 contiguous bytes.
    __global__ void add_coalesced(const float* a, const float* b, float* c, int rows, int cols) {
        int col = blockIdx.x * blockDim.x + threadIdx.x;
        int row = blockIdx.y * blockDim.y + threadIdx.y;
        if (row < rows && col < cols) {
            int idx = row * cols + col;
            c[idx] = a[idx] + b[idx];
        }
    }
    

    2. Vectorized loads (float4). Treating contiguous matrices as flat arrays of float4 (four floats = 16 bytes per load/store) lets each thread process 4 elements in one wide memory instruction, cutting total instructions and launched threads by 4x. It requires 16-byte pointer alignment and a small cleanup check when rows * cols is not divisible by 4. Because add_coalesced already saturates most of DRAM bandwidth, float4 gives a modest extra polish (often a few percent).

    __global__ void add_vec4(const float4* a, const float4* b, float4* c, int num_vec4) {
        int i = blockIdx.x * blockDim.x + threadIdx.x;
        if (i < num_vec4) {
            float4 va = a[i];
            float4 vb = b[i];
            c[i] = make_float4(va.x + vb.x, va.y + vb.y, va.z + vb.z, va.w + vb.w);
        }
    }
    

    3. Shared-memory staging. Shared memory is a fast, programmer-managed on-chip scratchpad shared by threads in the same block. For plain C = A + B, every element a[idx] and b[idx] is read once and never reused by any other thread. Copying from global DRAM into shared memory, waiting at a __syncthreads() barrier, and reading back out only adds latency and register/scratchpad pressure for zero DRAM savings! Shared-memory staging does pay off when data is reused (as in matrix multiplication A * B) or when read and write layouts conflict, such as transposed addition C = A + transpose(B): a block loads a 32 * 32 tile of B coalesced into __shared__ float tile[32][33] (where the +1 column avoids bank conflicts, which happen when multiple warp threads access different addresses that map to the same shared-memory bank and get serialized), synchronizes, and reads tile[tx][ty] while writing C coalesced.

    Which version wins? For plain C = A + B, the simple coalesced kernel (optionally widened to float4) is best: clean, minimal overhead, and right near peak DRAM throughput. An even bigger system-level win is kernel fusion — folding + b[idx] directly into the kernel that produced A or consumes C so the 201.3 MB intermediate matrix never round-trips to off-chip DRAM at all.

  7. Eliminate uniform redundant work for speed and battery power

    When thousands of GPU threads all compute the exact same formula or repeatedly load the same read-only value from global memory, every warp wastes instruction slots, memory requests, and milliwatts of battery power repeating identical work. Fix it by pushing uniform work as early and as high up the hierarchy as possible:

    1. Precompute once on the CPU (host) and pass by value: Compute scalars like scale = params[0] * expf(params[1]) / params[2] once on the CPU before launching the kernel, and pass float scale as a kernel argument. GPU kernel arguments sit in constant memory / uniform registers and broadcast to all 32 threads of a warp in a single read.
    2. Hoist loop-invariant reads into registers: Inside a per-thread loop, load unchanging values into local float variables before the loop, and mark non-overlapping input pointers const float* __restrict__ so the compiler knows writes to the output buffer cannot overwrite the input buffer (pointer aliasing) and can safely cache reads in registers.
    3. Use __constant__ memory for small warp-uniform tables: Small read-only arrays (up to 64 KB in CUDA, such as convolution filter weights or polynomial coefficients) where every thread in the warp reads the exact same index coeffs[k] at the same step belong in __constant__ memory, whose hardware cache broadcasts one read to the entire warp. (Never use __constant__ when threads in a warp index different entries — divergent constant-cache reads get serialized!)
    4. Specialize uniform branches and divisions: Replace repeated division by a uniform denominator x / d with multiplication by inv_d = 1.0f / d precomputed on the host (when 1-ULP rounding differences are acceptable), and use template booleans for launch-time flags to remove dead branches completely.
    __constant__ float coeffs[16];  // uploaded once from host via cudaMemcpyToSymbol
    
    // Host precomputes `scale` once; coeffs[k] broadcasts once per warp iteration.
    __global__ void scale_and_poly(const float* __restrict__ x, float* __restrict__ y,
                                   float scale, int degree, int n) {
        int i = blockIdx.x * blockDim.x + threadIdx.x;
        if (i < n) {
            float v = x[i] * scale;       // `scale` arrives via kernel-arg constant broadcast
            float acc = coeffs[degree];
            for (int k = degree - 1; k >= 0; --k) {
                acc = acc * v + coeffs[k]; // all 32 warp threads read coeffs[k]: 1 broadcast!
            }
            y[i] = acc;
        }
    }
    

    Why this matters even more for power than wall-clock speed: Moving data burns vastly more energy than arithmetic. In Mark Horowitz's classic 45 nm CMOS energy table (ISSCC 2014), a 32-bit floating-point add costs roughly 0.9 pJ, a 32-bit read from small on-chip SRAM costs ~5 pJ, and a 32-bit read from off-chip DRAM costs ~640 pJ — over 700 times the energy of an addition! Eliminating redundant per-thread DRAM loads and executing uniform math once on the host (or on hardware scalar units found in modern mobile and desktop GPUs) slashes heat and battery drain, preventing thermal throttling on power-constrained devices such as smartphones and embedded SoCs.

Intuition & how it works

All four parts of this interview question test one unifying systems engineering habit: separating what source code looks like on the page from what the compiler and hardware actually do underneath. Whether you are reading a C++ struct, calling a macro, or launching a GPU kernel, bugs and slowdowns appear whenever surface appearance diverges from physical reality — text paste vs typed calls, logical values vs padded memory bytes, or math operations vs off-chip memory traffic.

Naive intuition falls into predictable traps on all four sub-problems. Beginners assume sizeof(Pixel) equals the sum of its field sizes (ignoring hardware alignment padding), treat #define macros as "zero-overhead functions" (until SQUARE(i++) increments i twice), try to speed up GPU A + B by adding shared-memory staging (adding synchronization overhead to a kernel with zero data reuse), and let millions of GPU threads each recompute a shared constant from DRAM (burning 700x more energy per DRAM fetch than an addition).

Walking through tiny concrete examples makes each mechanism click immediately: - Enums & structs: In enum Color { Red, Green = 5, Blue };, Blue is 6. Initializing Pixel p{'x', 7}; on a 4-field struct {char, int, Color, Mode} zero-initializes the two omitted fields (0, 0), yet sizeof(p) is 16 bytes instead of 10 bytes because the compiler inserts 6 bytes of alignment padding (12 bytes once reordered largest-first). - Macros vs functions: #define SQUARE_BAD(x) x * x pastes SQUARE_BAD(1 + 2) literally as 1 + 2 * 1 + 2 = 5, whereas constexpr int square(int x) evaluates 1 + 2 = 3 once, returns 9, and compiles to the exact same machine code under -O2. - GPU bandwidth & uniformity: Adding two 4096 * 4096 float matrices moves 201.3 MB for 16.8M adds (0.083 FLOP/byte). Mapping threadIdx.x along columns lets a 32-thread warp (a group of 32 GPU threads executing in lockstep) fetch 128 contiguous bytes in one coalesced burst instead of 1,024 scattered bytes across 32 rows, and computing shared scalars once on the CPU avoids millions of redundant off-chip reads.

Key points

  • Enum numbering and scope: Enumerators start at 0 and increment by +1 from the previous value ({Red, Green = 5, Blue} -> 0, 5, 6). Unscoped enum leaks names into the enclosing scope and implicitly converts to int; enum class scopes names (Mode::On) and requires static_cast<int> to print as a number.
  • Stream printing depends on the exact integer type: std::uint8_t aliases unsigned char, so std::cout prints static_cast<std::uint8_t>(65) as the character 'A' rather than 65. Arithmetic like 'A' + 1 triggers integral promotion (automatic widening of sub-int types to int), printing 66.
  • Aggregate initialization rules: Braces {a, b} initialize struct fields in declaration order and zero-initialize omitted fields (unless a default member initializer like int retries = 3; is present), while rejecting narrowing conversions (double to int). A plain local declaration Config c; without braces leaves fields without default initializers holding indeterminate stack garbage (undefined behavior if read).
  • Values vs layout (sizeof and padding): Compilers insert padding bytes so every member sits at an address multiple of its alignment and struct arrays stay aligned. {char, int, Color, Mode} takes 16 bytes on 64-bit ABIs, whereas {int, Color, char, Mode} takes 12 bytes (25% smaller) with identical logical values.
  • Macros vs inline / constexpr functions: Macros run in the preprocessor as untyped text substitution — vulnerable to operator precedence bugs, double evaluation of arguments with side effects (MAX(i++, j)), namespace pollution, and opaque debugger traces. inline and constexpr functions evaluate each argument once, check types, preserve debug symbols, and generate identical assembly under optimization.
  • GPU matrix addition is memory-bound: Moving 12 bytes per single floating-point add (0.083 FLOP/byte) takes ~100x longer than the math on modern GPUs. Simple coalesced one-thread-per-element indexing (threadIdx.x along row-major columns) already runs close to peak DRAM bandwidth; float4 vectorized loads give a small extra boost; shared-memory staging hurts plain A + B (zero reuse) and only helps patterns like A + transpose(B); kernel fusion saves the entire DRAM pass.
  • Hoist uniform work for speed and energy: Compute thread-uniform scalars once on the CPU (passed by value as kernel arguments), cache loop-invariant values in registers (__restrict__), and place small warp-uniform tables in __constant__ memory for single-read warp broadcasts. Off-chip DRAM reads cost ~640 pJ per 32 bits vs ~0.9 pJ for an FP32 add (45 nm reference), so cutting redundant memory traffic dramatically improves battery life and sustained thermal performance.

Common mistakes

  • Casting a uint8_t-backed enum class to uint8_t for std::cout. Because std::uint8_t is unsigned char, std::cout prints an ASCII symbol (or an invisible control character for small enum values like 0 or 1!) instead of digits — cast to int instead.
  • Assuming local Struct s; zeroes its members. Only static/global variables or braced initializers (Struct s{};) zero fields that lack default member initializers; reading uninitialized local primitives is undefined behavior.
  • Assuming sizeof(Struct) equals the sum of member sizes, or using memcmp on structs. Uninitialized padding bytes sit between fields, so memcmp can return non-zero on two structs whose fields are all equal.
  • Parenthesizing macro parameters without parenthesizing the whole macro body (#define SQ(x) (x) * (x) still miscalculates 12 / SQ(2) as 12), or passing i++ / function calls into a macro.
  • Claiming macros beat inline functions in release builds without checking assembly. Modern optimizing compilers inline small typed functions cleanly while keeping type safety and single evaluation.
  • Mapping threadIdx.x to the row index of a row-major matrix. That makes the 32 threads of a warp step down a column cols * 4 bytes apart, fetching up to 8x more DRAM bytes than necessary.
  • Staging A and B through __shared__ memory in plain C = A + B. Because no two threads share an element, shared memory adds an extra copy and __syncthreads() barrier with zero DRAM traffic reduction.
  • Putting per-thread divergent lookups into __constant__ memory. Hardware constant cache broadcasts one address per warp per cycle; if 32 threads read 32 different table indices, the 32 reads serialize one after another.

Follow-up questions

  • How can you benchmark a GPU elementwise kernel to confirm it is memory-bound and quantify its achieved bandwidth efficiency? Time the kernel alone using GPU hardware events (cudaEventRecord) after at least one warm-up launch, averaged across many iterations without host-to-device cudaMemcpy calls inside the timer. Divide the mandatory bytes moved (3 * rows * cols * sizeof(float)) by the elapsed kernel time — for example, 201.3 MB / 0.25 ms = 805 GB/s, which is 80.5% of a 1 TB/s theoretical peak (and compare against a device-to-device cudaMemcpy buffer copy as the practical hardware ceiling). In a GPU profiler's roofline chart (a plot of achieved FLOP/s vs arithmetic intensity FLOP/byte), 0.083 FLOP/byte sits far to the left under the slanted memory-bandwidth ceiling, confirming that DRAM throughput — not compute — caps runtime.
  • Why is applying #pragma pack(1) to in-memory structs usually worse than reordering member fields? #pragma pack(1) forces alignment to 1 byte (shrinking Pixel from 16 bytes to 10 bytes), which causes multi-byte fields like int value to sit at misaligned memory addresses. On some CPU architectures misaligned loads require slower multi-cycle hardware fixups or extra shift-and-mask instructions, on stricter embedded cores they can trigger hardware alignment faults, and taking a typed pointer int* p = &packed.value; creates a misaligned pointer whose dereference is undefined behavior in standard C++. Instead, reorder struct members largest-to-smallest in RAM, and reserve explicit byte-by-byte serialization for network packets and binary files (which also handles endianness cleanly).
  • When are preprocessor macros still justified in modern C++ for assertions and diagnostic logging? Only the preprocessor sees the raw source text at the call site before evaluation: stringizing (#expr) turns ASSERT(x > 0) into the diagnostic string "x > 0", and conditional compilation (#ifdef NDEBUG) strips debug assertions or trace logs completely so expensive argument expressions are never even evaluated in release builds. In C++20, std::source_location::current() as a default function parameter replaces __FILE__ and __LINE__ cleanly without macros, so modern logging libraries use at most a tiny outer macro (for lazy evaluation or #expr) that immediately forwards into a type-safe C++ function.

Follow-up questions

Similar questions

More Qualcomm interview questions

All 4 Qualcomm questions →