1.

Define inline functions in C and C ++. Also, give an example of an inline function in C.

Answer»

An inline function in C or C++ is one that is declared with the keyword "inline". It serves two purposes:

  • It is a compiler directive that requests (it is not mandatory for the compiler to comply with the request of the inline function) that the compiler replaces the body of the function inline by performing inline expansion, that is, putting the function code at the location of each function call, hence reducing the overhead of a function call. It is SIMILAR to the register storage class specifier in this regard, which also gives an optimization indication. Inline functions are usually used for frequent calls to the same function.
  • The second GOAL of the keyword "inline" is to alter link behaviour. This is required by the C/C++ separate compilation and linkage model, notably because the function's definition (body) must be replicated in all translation units where it is used to allow inlining during compilation, which creates a collision during linking if the function has external linkage (it violates uniqueness of external symbols). This is handled differently in C and C++ (as well as dialects like GNU C and Visual C++).

An example of an inline function in C is given below:

inline void addNumbers(INT a, int b){ int ans = a + b; printf("SUM of the two numbers is: %d", ans);}

Let us say that the above inline function is called somewhere in the main function of the C program as:

int x = 10;int y = 20;addNumbers(x, y);

Here, the "addNumbers(x, y);" function call will be replaced by the following piece of code in the main function itself by the compiler:

int x = 10;int y = 20;int ans = x + y;printf("Sum of the two numbers is: %d", ans);


Discussion

No Comment Found