Is my code written correct ?
Jun 21, 2014 at 5:16pm UTC
I am new to pointers... I am just interest if my code is written correct. I know it has calculator ( ex. 5 + 10 ) + swap function inside which is kinda stupid...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
using namespace std;
void calculator(char oper, int x, int y);
void swap1 (int *x, int *y);
int main ()
{
int number1, number2;
char oper;
int *p_number1 = & number1;
int *p_number2 = & number2;
cout << "Enter your number" << '\n' ;
cin >> *p_number1 >> oper >> *p_number2;
calculator(oper, number1, number2);
cout << '\n' ;
cout << "number1 = " << *p_number1 << endl;
cout << "number2 = " << *p_number2 << endl;
swap1 (p_number1, p_number2);
cout << *p_number1 << " " << *p_number2 << endl;
cout << number1 << " " << number2;
}
void calculator (char oper, int x, int y)
{
switch (oper)
{
case '/' :
cout << x / y;
break ;
case '*' :
cout << x * y;
break ;
case '+' :
cout << x + y;
break ;
case '-' :
cout << x - y;
break ;
}
}
void swap1 (int *x, int *y)
{
swap(*x, *y);
}
Jun 21, 2014 at 5:35pm UTC
Yes. It is correctly written.
Just FYI: there is std::iter_swap() function which does exacly what you have written in your swap1 function
Jun 21, 2014 at 5:50pm UTC
I do know that you can make it simpler, tho I used function because of pointers :D. And thanks for your answer!
Topic archived. No new replies allowed.