« Inline And Default arguments
Understand Inline And Default arguments
Inline functions
1inline int max2(int a, int b)2{3 return a > b ? a : b;4}56int main()7{8 int a, b;9 cin >> a >> b;1011 int c = (a > b) ? a : b;12 c = max(a, b);13}
Each time it will go to the function and return the value and then value is pushed to c
. So a performance lag even though a very small one.
1int max(int a, int b)2{3 return a > b ? a : b;4}56int main()7{8 int a, b;9 cin >> a >> b;1011 int c = (a > b) ? a : b;12 c = max2(a, b);13}
For inline function compiler will copy the function body at the place where its getting called. So we made our code readable plus there is no performance lag.
Why not make all functions inline?
So if we try to make all functions (big functions) inline then:
a.out
file will be bulkier as the program will be huge.- When we write inline then we hint the compiler to please do it but its compiler's decision to do it or not
- If single line function compiler will do it, if 2-3 lines it might do or it might not, more than these number of lines it won't do
Default arguments
1int sum(int arr[], int size, int si = 0)2{3 int ans = 0;4 for (int i = si; i < size; i++)5 {6 ans = ans + arr[i];7 }8 return ans;9}
A Default value is given to si
. All default variables should be at the rightmost places in the function call.
- function sum(normal, default, normal, default) This will not throw an error but it can create confusion to the function that you passed value to which argument.
- function sum(normal, normal, default, default) this is correct
Final code
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int max(int a, int b)15{16 return a > b ? a : b;17}1819inline int max2(int a, int b)20{21 return a > b ? a : b;22}2324// default value given to si25int sum(int arr[], int size, int si = 0)26{27 int ans = 0;28 for (int i = si; i < size; i++)29 {30 ans = ans + arr[i];31 }32 return ans;33}3435int sum2(int arr[], int size, int si = 0, int m)36{37 int ans = 0;38 for (int i = si; i < size; i++)39 {40 ans = ans + arr[i];41 }42 return ans;43}4445int main()46{47 int a, b;48 cin >> a >> b;4950 int c = (a > b) ? a : b;51 c = max(a, b);52 c = max2(a, b);5354 int x, y;55 cin >> x >> y;5657 int z = (x > y) ? x : y;58 x = max(x, y);59 x = max2(x, y);6061 int arr[20];62 cout << sum(arr, 20, 0) << endl;63 cout << sum(arr, 20) << endl;64 // we can skip default values6566 cout << sum(arr, 20, 5) << endl;6768 cout << sum2(arr, 20, 5) << endl;6970 return 0;71}