Cracking C++ (6): Functions & Attributes

lamoon·2025년 8월 9일

Cracking C++

목록 보기
6/8

Function

Purpose: making programs easier to understand by breaking up into concise functions

  • export if function is for use by other modules (declare it from modle interface file while the function's definition can either be in same module interface file or in so-called module implementation file)

Function Declaration

Definition (i.e. function prototypes, function headers): represent how the function can be accessed (not the code behind it).

  • NOT function signature which denote combination of function name, parameter list but without the return type
  • Example: void foo(int i, char c);
    • without actual definition to match this declaration, link stage of compilation process fail
    void foo(int i, char c) { 
    	cout format("the value of i and c: {} {}", i, c) << endl;
    }
    • call this anywhere and pass two parameters (e.g. foo(8, 'a');)
    • Function that takes no parameter can have empty parameter list (in C, you have to use void)

Return Type Deduction

  • ask compiler to figure out return type automatically
auto add(int x, int y) { return x + y; }
  • compiler uses return statements in the body to deduce this - if there are multiple they must all resolve to same type
    • for recursive function, first return in the function must be non-recursive call

Current Function's name

__func__ contains name of current function

  • e.g. cout << format("Entering function {}", __func__) << endl;

Function Overloading

  • providing several functions with same name with different parameters (not just return types; number and/or types of parameters must be different)

Good Example

int addNumbers(int a, int b) { return a + b; }
double addNumbers(double a, double b) { return a + b; }

Attribute

Def'n: mechanism to add optional and/or vendor-specific info to source code

  • basically a note to the compiler to better understand the code

Types

  1. [[nodiscard]]: let the compiler issue a warning when a function's return value is ignored
  • used for functions that return error codes, so the result isn't ignored
  • [[nodiscard("msg")]] int func() available since C++20

Example

[[nodiscard]] int func() { return 42; }
int main() { func(); } // warning: discarding return value of function with 'nodiscard' attribute
  1. [[maybe_unused]]: suppress compiler warnings when something is unused

Example

int func(int param1, [[maybe_unused]] int param2) { return 42; }
// suppresses:
// warning C4100: 'param2': unreferenced formal parameter
  1. [[noreturn]]: never returns control to the call site - avoids compiler giving warnings (these are usually used for termination)

Example

[[noreturn]] void forceProgramTermination() { std::exit(1);}
// Suppresses warning C4715: 'isFeatureLicensed': not all control paths return a value
  1. [[deprecated]]:mark sth deprecated - still usable but discouraged. Issues a compiler warning
  • Variation: [[deprecated("Unsafe method, please use xyz")]] void func();
  1. [[likely]] and [[unlikely]] (C++20 and above): help compiler optimizing code by marking branches of if and switch statements according to how liekly is that branch will be taken
  • usually not needed but for certain performance critical code, we can help the compiler

Example

int value { /* ... */ };

if (value > 11) [[unlikely]] {
    // Do something ...
} else {
    // Do something else...
}

switch (value) {
    [[likely]] case 1:
        // Do something ...
        break;
    case 2:
        // Do something...
        break;
    [[unlikely]] case 12:
        // Do something...
        break;
    default:
        // Optional default handling...
        break;
}

0개의 댓글