1.

In C and C++, define inline functions. Also, show how to use an inline function in C.

Answer»

In C or C++, an inline function is one that is declared using the keyword "inline." It has two important features:

  • It is a compiler directive that requests that the compiler replace the body of the function inline by PERFORMING inline expansion, that is, placing the function code at the location of each function call, thus reducing the overhead of a function call (it is not mandatory for the compiler to comply with the REQUEST of the inline function). In this way, it is analogous to the register storage class specifier, which also provides an optimization indication. For frequent calls to the same function, inline functions are typically employed.
  • The second purpose of the keyword "inline" is to change the behaviour of LINKS. The C/C++ separate compilation and LINKAGE architecture necessitates this, in part because the function's definition (body) must be reproduced in all translation units where it is used to allow inlining during compilation, which causes a collision during linking if the function has external linkage (it violates uniqueness of external symbols). In C and C++ (as well as dialects like GNU C and Visual C++), this is handled differently.

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

inline VOID multiply(int x, int y){ int answer = x * y; printf("Product of x and y is the following: %d", answer);}

Let us assume that the above written inline function will be called inside the main function of the C program as follows:

int xval = 5;int yval = 4;multiply(xval, yval);

Here, the "multiply(xval, yval);" function call is going to be replaced in the main function itself by the compiler by the piece of code given below:

int xval = 5;int yval = 4;int answer = xval * yval;printf("Product of x and y is the following: %d", answer);


Discussion

No Comment Found