inline function in c example

Example of an Inline Function in C

Here is an example of an inline function in C:

#include <stdio.h>

// Inline function to calculate the square of a number
inline int square(int num) {
    return num * num;
}

int main() {
    int num = 5;
    int result = square(num);
    printf("The square of %d is %d\n", num, result);
    return 0;
}

Explanation

  1. The #include <stdio.h> directive is used to include the standard input/output library, which provides functions like printf() for printing output to the console.

  2. The inline keyword is used to define an inline function. Inline functions are a way to suggest the compiler to replace the function call with the actual function code at the call site, which can improve performance by avoiding the overhead of a function call.

  3. The square() function is defined as an inline function that takes an integer argument num and returns the square of that number.

  4. In the main() function, an integer variable num is declared and initialized with the value 5.

  5. The square() function is called with num as the argument, and the result is stored in the result variable.

  6. The printf() function is used to print the result to the console, with the format string "The square of %d is %d\n". The %d format specifier is used to print integer values.

  7. Finally, the return 0; statement is used to indicate successful program execution.

Note: The inline keyword is a suggestion to the compiler, and it may choose to ignore it. The compiler decides whether to inline a function based on various factors, such as the size of the function and the optimization settings.