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:
- Reasoning about
enumandstructprograms: Walk through how you determine the printed output and memory footprint of a C++ snippet that combinesenumtypes withstructobjects. Cover automatic enumerator value assignment, unscopedenumversus scopedenum 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. - Preprocessor
#definemacros versus C++ /inlinefunctions: Contrast function-like preprocessor macros with ordinary orinlineC++ functions across translation stage (text preprocessing versus compilation), static type checking, expression side effects and repeated argument evaluation, source-level debuggability, and runtime speed. - 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.
- 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::coutcharacter/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
inlineandconstexprfunctions. - 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
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
enumandstructprints, trace it in two separate steps: first work out each variable's numeric value, and second check the exact C++ type reachingstd::cout <<, becauseoperator<<formats characters, booleans, and integers differently.1. Enumerator numbering. Inside any
enum, the first name defaults to0if you do not give it a value, and every later name without an explicit value equalsprevious + 1. So inenum Color { Red, Green = 5, Blue };,Redis0,Greenis5, andBlueis6.2. Unscoped
enumvs scopedenum class. - An unscopedenum(enum Color) drops its names (Red,Green,Blue) straight into the surrounding scope, so two unscoped enums in the same namespace cannot both defineRed. It also implicitly converts to an integer orbool:std::cout << Blueprints6,Blue + 1evaluates to7, andbool ok = Blue;becomestrue. (Going the other way still requires an explicit cast:Color c = 5;is a compile error.) - A scopedenum(enum class Mode) keeps its names insideMode::(Mode::On) and blocks implicit conversions. Writingstd::cout << Mode::Onorint x = Mode::On;fails to compile; you must cast explicitly withstatic_cast<int>(Mode::On). - Underlying integer type:enum classusesint(4 bytes) unless you specify another integer type such as: std::uint8_t(1 byte). An unscopedenumwithout: Typelets 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_tis a type alias (typedef) forunsigned char. Becausestd::cout <<treatsunsigned charas a text character,std::cout << static_cast<std::uint8_t>(Mode::On)whenOn = 65prints the ASCII letterA, not65! Cast tointwhenever you want the numeric value. - Integral promotion is C++'s rule that arithmetic operators (+,-,*) automatically widen integer types narrower thanint(such ascharoruint8_t) tointbefore computing. Sochar c = 'A';printsAon its own, whereasc + 1has typeintand prints66. - Aboolprints1or0by default unlessstd::boolalphais 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 }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 likeint retries = 3;).When a
structis 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 to0, pointers tonullptr, and enums tostatic_cast<EnumType>(0)— even if the enum never defined an enumerator equal to0! 2. No narrowing inside braces: Curly braces reject narrowing conversions (conversions that can lose information, such asdoubletoint).Pixel q{'x', 7.5};fails to compile, whereasint v = 7.5;compiles and truncates7.5to7.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, andb(castingp.modetoint), we getx 7 0 0,3 0 0, and5 0 0. By contrast, readingc.scaleorc.coloris undefined behavior (UB) (code whose result the C++ standard places no requirements on, allowing garbage outputs or optimizer surprises).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), comparePixelagainst 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 arrayPixel arr[2].arr[1]sits immediately at byte offsetsizeof(Pixel). Without those 3 tail bytes,arr[0]would be 13 bytes long, placingarr[1].valueat byte13 + 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,
PixelCompacttakes 12 MB instead of 16 MB, saving 4 MB of cache and memory bandwidth for free. - Never compare or hash structs withmemcmp: padding bytes contain unspecified leftover memory, so twoPixelobjects with identical member values can differ in their padding bytes and failmemcmp(&p1, &p2, sizeof(Pixel)) == 0. Always compare field by field (or usebool operator==(const Pixel&) const = default;in C++20).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, orconstexprfunction 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 * xexpandsSQUARE_BAD(1 + 2)into1 + 2 * 1 + 2, which evaluates to5instead of9! Even#define SQUARE_HALF(x) (x) * (x)fails on12 / SQUARE_HALF(2), expanding to12 / (2) * (2) = 12instead of3. 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 fromi = 5, j = 3, the condition checks5 > 3(ibecomes6), and then the true branch runsi++a second time, returning6and leavingi == 7! Worse,SQUARE(i++)expands to((i++) * (i++)), modifyingitwice without sequencing — undefined behavior. A C++ function evaluates each argument exactly once before entering the body:max_of(i++, j)returns5and leavesi == 6. - Type safety and scope: Macros ignore types (
MAX(2, 3.5)silently mixesintanddouble) and ignore namespaces (defining#define max ...in a header breaksstd::maxeverywhere 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++, theinlinekeyword primarily satisfies the One Definition Rule (ODR) (allowing an identical function definition to appear in a header included by multiple.cppfiles without linker duplicate-symbol errors), whileconstexpradditionally lets the compiler evaluate calls likesquare(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 == 6Keep macros only for jobs the language itself cannot express: conditional compilation (
#ifdef), stringizing an expression (#exprin custom assertions), or token pasting (a##b).- Operator precedence bugs:
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 two4096 * 4096matrices of 32-bitfloat(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 msBecause 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.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.xvaries fastest across threads0..31of 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 offloat4(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 whenrows * colsis not divisible by 4. Becauseadd_coalescedalready saturates most of DRAM bandwidth,float4gives 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 elementa[idx]andb[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 multiplicationA * B) or when read and write layouts conflict, such as transposed additionC = A + transpose(B): a block loads a32 * 32tile ofBcoalesced into__shared__ float tile[32][33](where the+1column 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 readstile[tx][ty]while writingCcoalesced.Which version wins? For plain
C = A + B, the simple coalesced kernel (optionally widened tofloat4) 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 producedAor consumesCso the 201.3 MB intermediate matrix never round-trips to off-chip DRAM at all.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:
- 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 passfloat scaleas 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. - Hoist loop-invariant reads into registers: Inside a per-thread loop, load unchanging values into local
floatvariables before the loop, and mark non-overlapping input pointersconst 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. - 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 indexcoeffs[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!) - Specialize uniform branches and divisions: Replace repeated division by a uniform denominator
x / dwith multiplication byinv_d = 1.0f / dprecomputed 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.
- Precompute once on the CPU (host) and pass by value: Compute scalars like
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
0and increment by+1from the previous value ({Red, Green = 5, Blue}->0, 5, 6). Unscopedenumleaks names into the enclosing scope and implicitly converts toint;enum classscopes names (Mode::On) and requiresstatic_cast<int>to print as a number. - Stream printing depends on the exact integer type:
std::uint8_taliasesunsigned char, sostd::coutprintsstatic_cast<std::uint8_t>(65)as the character'A'rather than65. Arithmetic like'A' + 1triggers integral promotion (automatic widening of sub-inttypes toint), printing66. - Aggregate initialization rules: Braces
{a, b}initialize struct fields in declaration order and zero-initialize omitted fields (unless a default member initializer likeint retries = 3;is present), while rejecting narrowing conversions (doubletoint). A plain local declarationConfig c;without braces leaves fields without default initializers holding indeterminate stack garbage (undefined behavior if read). - Values vs layout (
sizeofand 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/constexprfunctions: 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.inlineandconstexprfunctions 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.xalong row-major columns) already runs close to peak DRAM bandwidth;float4vectorized loads give a small extra boost; shared-memory staging hurts plainA + B(zero reuse) and only helps patterns likeA + 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-backedenum classtouint8_tforstd::cout. Becausestd::uint8_tisunsigned char,std::coutprints an ASCII symbol (or an invisible control character for small enum values like0or1!) instead of digits — cast tointinstead. - 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 usingmemcmpon structs. Uninitialized padding bytes sit between fields, somemcmpcan 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 miscalculates12 / SQ(2)as12), or passingi++/ function calls into a macro. - Claiming macros beat
inlinefunctions in release builds without checking assembly. Modern optimizing compilers inline small typed functions cleanly while keeping type safety and single evaluation. - Mapping
threadIdx.xto the row index of a row-major matrix. That makes the 32 threads of a warp step down a columncols * 4bytes apart, fetching up to 8x more DRAM bytes than necessary. - Staging
AandBthrough__shared__memory in plainC = 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-devicecudaMemcpycalls 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 a1 TB/stheoretical peak (and compare against a device-to-devicecudaMemcpybuffer copy as the practical hardware ceiling). In a GPU profiler's roofline chart (a plot of achievedFLOP/svs arithmetic intensityFLOP/byte),0.083 FLOP/bytesits 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 (shrinkingPixelfrom 16 bytes to 10 bytes), which causes multi-byte fields likeint valueto 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 pointerint* 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) turnsASSERT(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
- How can you benchmark a GPU elementwise kernel to confirm it is memory-bound and quantify its achieved bandwidth efficiency?
- Why is applying #pragma pack(1) to in-memory structs usually worse than reordering member fields?
- When are preprocessor macros still justified in modern C++ for assertions and diagnostic logging?
Similar questions
- Diameter of an Unweighted Tree
- Earliest Faulty Build in Version History
- A* Grid Maze Pathfinding
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
More Qualcomm interview questions
- Diameter of an Unweighted Tree Medium
- Earliest Faulty Build in Version History Medium
- A* Grid Maze Pathfinding Medium Pro