C Inline Function

1. What is an Inline Function?

  • An inline function suggests to the compiler to replace the function call with the function code itself.

  • This can reduce function call overhead and increase performance for small functions.

  • Declared using the inline keyword.

Syntax:

inline return_type function_name(parameters) {
// function body
}

Note: inline is a request to the compiler, not a command. The compiler may ignore it.


2. Example of Inline Function

#include <stdio.h>

inline int add(int a, int b) {
return a + b;
}

int main() {
int x = 5, y = 10;
int sum = add(x, y); // function call replaced by code
printf(“Sum = %d\n”, sum);
return 0;
}

Output:

Sum = 15
  • Instead of calling add(), the compiler may replace it with x + y in the code.


3. When to Use Inline Functions

  • Inline functions are suitable for small, frequently called functions.

  • Examples:

    • Getters/setters

    • Simple calculations

    • Tiny utility functions

Avoid inline for:

  • Large functions (increases code size)

  • Functions with loops, recursion, or complex logic


4. Inline Function vs Macro

Feature Inline Function Macro
Type checking Yes No
Debugging Easier Harder
Scope Respects scope Global
Safety Safer (evaluates once) Risk of multiple evaluation

Example using Macro vs Inline Function

#include <stdio.h>
#define SQUARE(x) ((x)*(x)) // macro
inline int square(int x) { return x * x; } // inline function

int main() {
int a = 5;
printf(“Macro: %d\n”, SQUARE(a));
printf(“Inline: %d\n”, square(a));
return 0;
}

Output:

Macro: 25
Inline: 25

Inline functions are type-safe and generally preferred over macros.


5. Key Points About Inline Functions

  1. Declared using inline keyword.

  2. Reduces function call overhead.

  3. Best for small, frequently used functions.

  4. Safer and type-checked compared to macros.

  5. Compiler may ignore the inline request if optimization isn’t suitable.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *