Your cal function doesn't need all of those variables. It takes operands and an operator, then returns one result, so you only need to store the result:
double cal(double num1, double num2, char op)
{
double result;
if (op == '+')
result = num1 + num2;
else if (op == '-')
result = num1 - num2;
else if (op == '*')
result = num1 * num2;
else
throw runtime_error("Unrecognized operator");
return result;
}
Since op is a char you can also use a switch instead of a bunch of if statements:
double cal(double num1, double num2, char op)
{
double result;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
default:
throw runtime_error("Unrecognized operator");
}
return result;
}
And you can tighten up the switch by returning directly and removing the result variable completely. :)
double cal(double num1, double num2, char op)
{
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
default:
throw runtime_error("Unrecognized operator");
}
}
Quote
I have got some problem with passing pointers and arrays in functions , can anyone please write little easy tutorial with example so that I can understand easily?
When you pass an array to a function, it always decays into a pointer to the first element. An array of ints becomes a pointer to int and the address is &array[0]. An array of arrays of int--a 2D array--becomes a pointer to an array of int and the address is &array[0].
Because it's a pointer, you can change the elements and the array you passed will change too. You also don't know the size of the array because it's a pointer, so you need to pass the size. That's all there is to it:
#include <iostream>
using namespace std;
void function(int *oned, int n, int (*twod)[5], int x, int y)
{
for (int i = 0; i < n; i++)
oned[i] *= oned[i];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++)
twod[i][j] *= 2;
}
}
int main()
{
int array1[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int array2[2][5] = {
{0, 1, 2, 3, 4},
{5, 6, 7, 8, 9}
};
cout << "Before calling function:\n";
for (int i = 0; i < 10; i++)
cout << array1[i] << ' ';
cout << '\n';
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++)
cout << array2[i][j] << ' ';
cout << '\n';
}
function(array1, 10, array2, 2, 5);
cout << "\nAfter calling function:\n";
for (int i = 0; i < 10; i++)
cout << array1[i] << ' ';
cout << '\n';
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++)
cout << array2[i][j] << ' ';
cout << '\n';
}
}
If you don't like the pointer notation in function parameters, you can use array notation too. The first dimension isn't required because the size is irrelevant, it's a pointer after all:
void function(int oned[], int n, int twod[][5], int x, int y)
This is exactly the same as the example. Your compiler will turn it into this:
void function(int *oned, int n, int (*twod)[5], int x, int y)