Posted in: C++

C++ program to find square of a Number using inline function

In this article, we are going to write a C++ program to find the square of a Number using the inline function. Before we write a c++ program to find the square of a variable using the inline function let’s first discuss the Inline function its uses, advantages, and disadvantages.

Inline Function

C++ program to find square of a Number using inline function.

To eliminate the cost of calls to small functions C++ proposes a new feature called the inline function. The inline function is the optimization technique used by the compilers.

Here are some of key points of inline function

  • An inline function is a function i.e expanded in a line.
  • It is invoked, the compiler replaces the function call with the corresponding code of the function.
  • The inline function is a request, not a Command.
  • The inline function does not contain a loop, switch statement, and goto statement.

In other words, the inline function is a powerful concept commonly used with classes. If a function is inline the compiler places a copy of the code of that function at each point where the function is called at compile time.

Advantages of Inline function

  • It does not require function calling overhead.
  • It saves the overhead of variables push/pop on the stack, while function calling.
  • The inline function reduces the execution time.

Disadvantages of Inline function-

  • May increase function size so that it may not fit on the cache, causing lots of cache miss.
  • If used in the header file, it will make your header file size large and may also make it unreadable.
  • It may cause compilation overhead as if somebody changes code inside the inline function then all calling locations will also be compiled.

After going through this topics you’re now familiar with Inline function so let’s write a program to get input by the user and square that number.

Program

// Simple C++ program to display "Square of a number" 
 

#include<iostream>
using namespace std;
inline int sqr(int x)
{
    return x*x;
}
int main()
{
    int x;
    cout<<"Enter a number : ";
    cin>>x;
    cout<<"Square of the number : "<<sqr(x);
    return 0;
}

Output

After writing the C++ program to square the number of inputted number using inline function, let’s check the output.

C++ program to find square of a Number using inline function.

If you have any questions or feedback please comment down below . Thank You

Leave a Reply

Your email address will not be published.