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
The
#include <stdio.h>
directive is used to include the standard input/output library, which provides functions likeprintf()
for printing output to the console.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.The
square()
function is defined as an inline function that takes an integer argumentnum
and returns the square of that number.In the
main()
function, an integer variablenum
is declared and initialized with the value5
.The
square()
function is called withnum
as the argument, and the result is stored in theresult
variable.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.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.