ReviseAlgo Logo

Functions

Function Basics

Defining and calling functions

Interview: Fundamental concept

Function Basics

Functions encapsulate reusable logic, reducing code duplication and enabling modular design. In C++, functions are first-class entities at the namespace level. Every C++ program starts from int main(), the special program entry point mandated by the standard.

Declaration vs Definition

A declaration (prototype) tells the compiler the function's signature without providing the body. A definition provides the body. You can declare a function many times but define it only once (One Definition Rule — ODR).

Stack Frame and Call Mechanism

Each function call pushes a stack frame onto the call stack, containing local variables, the return address, and saved registers. When the function returns, the frame is popped. Deep recursion can exhaust stack space, causing a stack overflow.

Interview Corner

Q: What is the One Definition Rule (ODR)?

A: The ODR states that any given non-inline function must have exactly one definition across all translation units in a program. Multiple declarations are allowed, but multiple definitions cause linker errors. Inline functions and templates have an exception — they can be defined in multiple translation units but all definitions must be identical.

Q: What does [[nodiscard]] do on a function?

A: The [[nodiscard]] attribute (C++17) causes a compiler warning if the return value of the function is ignored by the caller. It's used on functions where ignoring the return value is almost certainly a bug — like error codes, allocations, or computational results.

Common Pitfalls

  • Missing return statement: A non-void function without a return produces undefined behavior (compiler may warn but often allows it).
  • Returning local variable references: Returning a reference or pointer to a local variable is undefined behavior — the stack frame is destroyed after the function returns.

Best Practices

  • Use [[nodiscard]] on functions returning error codes or critical values.
  • Keep functions short and focused on a single responsibility (Single Responsibility Principle).
  • Use const correctness — declare parameters const when not modifying them.