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
inlinekeyword.
Syntax:
Note:
inlineis a request to the compiler, not a command. The compiler may ignore it.
2. Example of Inline Function
Output:
-
Instead of calling
add(), the compiler may replace it withx + yin 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
Output:
Inline functions are type-safe and generally preferred over macros.
5. Key Points About Inline Functions
-
Declared using
inlinekeyword. -
Reduces function call overhead.
-
Best for small, frequently used functions.
-
Safer and type-checked compared to macros.
-
Compiler may ignore the inline request if optimization isn’t suitable.
