Explain C++ Inline Semantics and Trade-Offs
Company: Hudson
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
# Explain C++ Inline Semantics and Trade-Offs
Explain what the C++ `inline` keyword means, how that differs from a compiler actually substituting a function body at a call site, what call-site expansion can improve, and what can go wrong when too much code is expanded.
### Constraints & Assumptions
- Cover modern C++ rather than treating `inline` as a guaranteed optimization command.
- Distinguish language linkage and one-definition-rule semantics from optimization.
- Consider templates, header-defined functions, link-time optimization, and shared-library boundaries where relevant.
### Clarifying Questions to Ask
- Is the focus language rules, performance, binary size, or all three?
- Should inline variables and implicitly inline member functions be included?
- Are separate translation units and link-time optimization part of the build?
- Does the system have instruction-cache or binary-size constraints?
### Hints
- A compiler can inline a function with no `inline` keyword and decline one that has it.
- Think about definitions that appear in more than one translation unit.
- Evaluate whole-program performance rather than assuming removal of a call is always faster.
### What a Strong Answer Covers
- The one-definition-rule allowance for identical reachable inline definitions across translation units.
- Implicit inline cases and why header definitions often need these semantics.
- Compiler cost models, link-time optimization, devirtualization, constant propagation, and call overhead.
- Code growth, instruction-cache pressure, compile time, debugging, ABI, and rebuild trade-offs.
- Recursive functions, address-taking, virtual dispatch, and cases where only some calls are expanded.
- Measurement through optimized builds and representative workloads.
### Follow-up Questions
1. Can a compiler inline a function whose address is taken?
2. Why can inlining a tiny hot function still reduce performance?
3. How does link-time optimization change what the compiler can see?
4. What happens if inline definitions differ across translation units?
Quick Answer: Explain that C++ inline semantics permit suitable definitions across translation units but do not require call-site expansion. Evaluate compiler optimization opportunities against code growth, instruction-cache pressure, build time, debugging, ABI, and measured workload performance.