0

Write a c++ program addition of two numbers

function overloading

10th Jul 2018, 1:27 AM
Gururaj kulkarni
3 Antworten
+ 10
Please show your own attempts.
10th Jul 2018, 1:37 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Hatsy Rei I love u! ;D Gururaj kulkarni You can achieve such functionality using at least two approaches, 1. function overloading plus (specifying one of the parameters as return type -- old-school style) 2. template function (just :-] ) Example of the function overloading void f(int &a, int b) { a+=b; } void f(float &a, float b) { a+=b; } void f(double &a, double b) { a+=b; } void f(long long &a, long long b) { a+=b; } void f(__int128 &a, __int128 b) { a+=b; } int main() { int a = 4, b = 6; f(a, b); cout << a; } And the result of addition would be assigned to variable a (using a third variable c as the result holder is necessary when the current value of a needs to be retrievable e.g. void f(int a, int b, int &c) { c=a+b })
10th Jul 2018, 9:18 AM
Babak
Babak - avatar
+ 4
Cont. Example of the template function. A template will be deduced the type of the args during compilation time. template <typename T> T f(T a, T b) { return a+b; } int main() { cout << f<>(4, 1) << endl; cout << f<>(4.5, 1.2) << endl; cout << f<>(37884312345433, 23487772228844) << endl; }
10th Jul 2018, 9:24 AM
Babak
Babak - avatar