C++ Functions for Beginners: Parameters, Returns, inline, Overloads, Defaults

C++ Functions for Beginners: Parameters, Returns, inline, Overloads, Defaults

이 글의 핵심

From prototypes to overloading: how to structure functions, pass arguments efficiently, satisfy return rules on all paths, and avoid ambiguous overloads and default-argument traps.

Why functions?

Functions remove duplication and name behavior.

Basic shape

ReturnType name(Parameters) {
    // body
    return value; // if not void
}

Return rules (summary)

  • Non-void functions must return on all paths (modern compilers warn/error).
  • main may omit return 0; (special case).
  • Returning large objects by value is fine—RVO/move often apply.
  • Never return references/pointers to locals.

Parameters

  • By value: copies; safe for small types.
  • By reference: aliases; efficient for large objects; use const& for read-only.
  • By pointer: can express “optional” with nullptr.

Default arguments

Defaults bind from the right; omit only trailing parameters. Put defaults on declarations (usually headers), not redundantly on definitions.

Overloading

Same name, different parameter lists—not by return type alone. Name mangling distinguishes overloads.

inline

Suggests inline expansion and affects ODR for definitions in headers—compiler has final say.

Recursion

Classic factorial/Fibonacci examples—watch stack depth and exponential Fibonacci; prefer iterative or memoization for real use.

Common mistakes

  • Calling before declaration—add prototypes or reorder.
  • Missing returns on some paths.
  • Passing std::vector by value unintentionally—use const vector<int>&.

Practical examples

The Korean article includes a menu-driven calculator, string utilities (case change, palindrome, word count), and array sort/search utilities—patterns are standard library–adjacent exercises.

Common problems (lifetime)

Returning &local or T& to locals → dangling. Return by value or refer to stable storage.

Overload ambiguity

Add overloads or explicit casts when float sits between int and double candidates.

Default argument + declaration split

Defaults belong on the declaration side of the interface, not duplicated on the definition.


  • Function overloading
  • Default arguments
  • Classes and objects

Practical tips

Debugging

  • Warnings; -Wreturn-type.

Performance

  • const refs; algorithms from <algorithm>.

Code review

  • Clear ownership and error handling.

Practical checklist

Before coding

  • API shape clear?

While coding

  • All paths return?

During review

  • Copies intentional?

C++, functions, parameters, return, overloading


  • Classes and objects