C++ Code Compilation and Behavior Quiz

Jul 11, 2024

C++ Code Compilation and Behavior Quiz

General Information

  • Game to assess understanding: "Don't do this at work".
  • Rules:
    • Presenter shows a code snippet.
    • Audience decides if it compiles and predicts the output.
    • Participants shout answers, with 5 to 10 seconds per question.
    • Assume C++ 20.

Code Snippets and Solutions

Boolean Incrementation

  • Snippet: bool b = true; ++b; printf("%d", b);
  • Question: Does it compile? What's the output?
  • Answer: No, because boolean incrementation was deprecated in C++17.

Char Array with Pi

  • Snippet: char arr[3] = "Pi"; printf("%s", arr);
  • Question: What's the output?
  • Answer: The null terminator maintains the string, so output is Pi.

3D Array Conversion

  • Snippet: Assign 3D array to a 2D pointer.
  • Question: Does it compile? What's the output?
  • Answer: Doesn't compile, requires unsigned char pointer of array type.
  • Alternative: If using correct type, it prints true.

Array Indexing Trick

  • Snippet: Indexing with integer on array.
  • Question: Does it compile?
  • Answer: Yes, equivalent to adding addresses and dereferencing.

Variadic Function with Fold Expressions

  • Snippet: Variadic function with unfold: func(args...)
  • Question: Does it compile?
  • Answer: Yes, unfolds to a calculation and results in 6.

Struct with Bit Field Overflow

  • Snippet: Bit manipulation within struct with bit field.
  • Question: Does it compile? What's the output?
  • Answer: Compiles, results in an overflow and prints 2.
  • Additional: Could be implementation-defined behavior.

Aggregate Initialization for Structs

  • Snippet: Struct initialized out of member order.
  • Question: Does it compile? What's the output?
  • Answer: Doesn't compile, members must be initialized in order.
  • Note: Rust-like syntax works in GCC and Clang, not MSVC.

Templated Lambda with Explicit Type

  • Snippet: Templated lambda with explicit int type.
  • Question: Does it compile?
  • Answer: No, cannot specify explicit type on templated lambda.

Constant Evaluated Function

  • Snippet: if consteval function returning different values based on evaluation.
  • Question: What’s the output?
  • Answer: Varies; consteval generally ensures certain behavior.

Struct Inheritance and Operator Overloading

  • Snippet: Complex struct inheritance example.
  • Question: Does it compile? What's the output?
  • Answer: Compiles; used pattern for std::visit, possibly causing a conversion error.

T1 and T2 Inheritance with Operator Overloading

  • Snippet: Struct hierarchy with call operator overload.
  • Question: What's the output?
  • Answer: bang bang question mark. The special member function call overrides the template deduction guide.