# Am I using pointers correctly?

I'm a newb at C++ and I was wondering whether I used pointers correctly and whether it was appropriate to use them in this context.

Any other tips/information would be appreciated.

#include <iostream>

using namespace std;

int euclideanAlgorithm(int *a, int *b);

int main() {
int x, y, a, b;
cin >> a;
cin >> b;
x = a;
y = b;
cout << x / euclideanAlgorithm(&a, &b) * y << endl;
return 0;
}

int euclideanAlgorithm(int *a, int *b) {
if (*b == 0) {
return *a;
}
while (*a >= *b) {
*a -= *b;
}
euclideanAlgorithm(b, a);
}

-
Just FYI, this prints out the lowest common multiple of the two integers input. – Wk_of_Angmar Feb 25 '13 at 0:59
Don't use using namespace std; See stackoverflow.com/q/1452721/14065 – Loki Astari Feb 25 '13 at 4:37

If you come from C and you start using C++, you might be use to have pointers whenever you want a function to be able to update one of its parameter. In C++, if you want to do so, you can use references which gives you a clearer and slightly safer result. Please refer to the wiki page for more details.

However, I'd like to point out that whenever you compute the lowest common multiple of the two integers, you probably don't want to change the value of this integers.

Thus, I'd expect the following code to do what you are trying to achieve (not tested, not even compiled):

#include <iostream>

using namespace std;

int euclideanAlgorithm(int a, int b);

int main() {
int a, b;
cin >> a;
cin >> b;
cout << a / euclideanAlgorithm(a, b) * b << endl;
return 0;
}

int euclideanAlgorithm (int a, int b) {
return (b == 0) ?
a :
euclideanAlgorithm(b, a % b);
}


Then, regarding the style : you can avoid forward declaration by changing the order of the functions. Also, it would probably be better to call you function with a shorter but still more explicit name such as gcd (hiding the implementation details : whether you use Euclid's algorithm or Wk_of_Angmar's algorithm shouldn't make any big difference for the one who is using the function).

-