Code Bloating in C++ with Examples

In this tutorial, we will be learning Code Bloating in C++ with some examples.

Whenever a programmer has to write a code using C++, He/She has to ensure that the code is fast and efficient. The programmer has to find a solution to the problem in such a way that the code does not take up too much memory.
Code bloat is the piece of code that a programmer writes which is slow, unnecessary and takes up a lot of unnecessary memory.

This is also a problem that causes a lot of trouble while developing software because this makes the code very long. To write quality code, the programmer must avoid code bloating at all costs.

Reasons For Code Bloating

Programmers face code bloating because of the given reasons:

  • Using Headers: When the programmers use headers for their code, they might involve some functions in their code. If the functions are not being used in their code and the header is present then it will still compile the function which causes an unnecessary delay for the programmers.
  • Using Templates: While using templates, the programmers have to change the values of functions and if the values are not changed then it makes the code compilation slow.

Now I will show how using headers cause code bloating with example code using C++ as the programming language:

#include <vector> 
int findSum(vector<int>& a, int A) 
{ 
    int s = 0; 
    for (int i = 0; i < A; i++) { 
        s += a[i]; 
    } 
    return s; 
} 
  
struct GfG { 
  
    
    std::vector<int> a; 
  
    // Function 
    int execute() const
    { 
        return findSum(a, a.size()); 
    } 
};

When the programmer codes the given piece of code, the functions findSum() and execute() compile every single time which causes code delay.

Example Program: Code Bloating in C++

#include <iostream> 
using namespace std; 
  
 
int main() 
{ 
    // Code Bloating 
    string str("Example for code bloating"); 

    cout << str << endl; 
    return 0; 
}

When the programmer codes the given program, the program runs and perfectly gives the output. However, this code creates an object in the class “string” to print the result.
This causes a delay in the execution. To tackle this the programmer can write the following piece of code instead

#include<iostream.h>
void main()
{
cout<<"Example for code bloating";
getch()
}

Hence, this code tackles the problem of code bloating.

Also, check out Create a Digital Clock in C++

Leave a Reply

Your email address will not be published. Required fields are marked *