Inline Functions in c++

 Inline Functions


C++ has a feature called inline functions to make programs run faster by reducing the time it takes to call a function.
Instead of jumping to the functions code when called, the compiler directly replaces the function call with the actual
code of the function during compilation. This can make the program more efficient, especially for small functions.

syntax:

inline return-type function-name(parameters)
{
    // function code
}  


#include <iostream>
using namespace std;

inline int square(int x) {
    return x * x;
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    cout << "The square of " << num << " is " << square(x*x) << endl;

    return 0;
}

#include <iostream>
using namespace std;

class Rectangle {
private:
    double length;
    double width;

public:
    Rectangle(double l, double w){
        length = l;
        width = w;
    }

    inline double area(){
        return length * width;
    }

    inline double perimeter(){
        return 2 * (length + width);
    }

    inline void displayDimensions(){
        cout << "Length: " << length << ", Width: " << width << endl;
    }
};

int main() {
    Rectangle rect(10.5, 5.5);

    rect.displayDimensions();
    cout << "Area: " << rect.area() << endl;
    cout << "Perimeter: " << rect.perimeter() << endl;

    return 0;
}




#include <iostream>

using namespace std;

class operation {
    int a, b, add, sub, mul;
    float div;

public:
    void get();
    void sum();
    void difference();
    void product();
    void division();
};
inline void operation ::get()
{
    cout << "Enter first value:";
    cin >> a;
    cout << "Enter second value:";
    cin >> b;
}

inline void operation ::sum()
{
    add = a + b;
    cout << "Addition of two numbers: " << add<< "\n";
}

inline void operation ::difference()
{
    sub = a - b;
    cout << "Difference of two numbers: " << sub<< "\n";
}

inline void operation ::product()
{
    mul = a * b;
    cout << "Product of two numbers: " <<mul << "\n";
}

inline void operation ::division()
{
    div = a / b;
    cout << "Division of two numbers: " <<div<< "\n";
}

int main()
{
    cout << "Program using inline function\n";
    operation s;
    s.get();
    s.sum();
    s.difference();
    s.product();
    s.division();
    return 0;
}

Comments

Popular posts from this blog

programs of oops in c++

Basic DSA programs in c++

C++ Exception Handling and file handling