Code Bloating in C++ with Examples
Last Updated :
31 May, 2020
Improve
Code bloat is the production of code that is perceived as unnecessarily long, slow, or otherwise wasteful of resources. It is a problem in Software Development which makes the length of the code of software long unnecessarily. So for writing the quality code, we always avoid code bloating in our program.
Following are some reasons for the Code Bloating:
CPP
- Headers: Suppose we have declare some functions in Header File as shown below:
CPP #include <vector> // Function to find the sum of elements // in a vector inline int findSum(vector<int>& arr, int N) { int sum = 0; for (int i = 0; i < N; i++) { sum += arr[i]; } return sum; } struct GfG { // Declare vector arr std::vector<int> arr; // Function int execute() const { return findSum(arr, arr.size()); } };
- Templates:
In C++ we have built-in templates for functions and containers. Templates are the generalized form of functionality with different data types. Every instance of a template is a completely separate piece of code generated by the compiler.
Consider below an example for templates:
CPP template <class T> T findSum(const T* arr, int num) { return accumulate(arr, arr + num, T(0)); } template <class T, int N> struct GfG { T arr[N]; T run() const { T res = 0; for (int i = 0; i < N; i++) res += arr[i]; return res; } };
- Define template functions in source file and explicitly instantiate them.
- Use extern template declarations in header, combined with explicit template instantiations in source files itself.
#include <iostream>
using namespace std;
// Driver Code
int main()
{
// Code Bloating
string str("GeeksForGeeks");
// Print string str
cout << str << endl;
return 0;
}
Output:
The above program will work perfectly and will print GeeksForGeeks. But there is a problem of code bloating in above program in first line of main function. The agenda of above program is to print the string GeeksForGeeks, So why we are creating object of string class as it result in creating string class object.
We simply could write
GeeksForGeeks
cout << "GeeksForGeeks" << endl;Effects of Code Bloat:
- It creates object of some classes unnecessarily that can make our software slow in execution.
- It is a problem in Software Development which made the length of code of software long unnecessarily.