Posts Tagged ‘C++’

Which is better…(int* nPtr) vs (int *nPtr)?

February 24, 2011 Leave a comment

Compare 2 functions in the main.cpp

#include <iostream>

using std::cout;
using std::endl;

int fn_CubeByValue(int);
void fn_CubeByReference(int *);

int main()
	int number, result;
	number = 5;

	cout << "number =" << number;
	result = fn_CubeByValue(number);
	cout << "\n after result = fn_CubeByValue(number);, number =" << number;
	cout << "\n, result =" << result;

	cout << "========================================";
	cout << "\nnumber =" << number;
	cout << "\nafter fn_CubeByReference(&number), number =" << number <<endl;


int fn_CubeByValue(int n)
	return n*n*n;

void fn_CubeByReference(int *nPtr)
	*nPtr = *nPtr * *nPtr * *nPtr;

In the first function, fn_CubeByValue, if I were to compare

int fn_CubeByValue(int n)


result = fn_CubeByValue(number);

, I would equate int n and number, represented by n <– number.

What if I use the same analogous to the second function, fn_CubeByReference, I would get that  int *nPtr must be equated to &number, that is, *nPtr<–&number which is not semantically true because *nPtr is would take a variable whereas &number is address.

Perhaps it makes more sense to say nPtr<–&number which indirectly conveys that we should write int* nPtr instead of int *nPtr. In which case we can interpret that the input nPtr takes value of type int* (indicating memory address). However, one can argue that another way to interpret int *nPtr is to say nPtr is the input variable taken by the function, but “int” restricts that whatever in “*nPtr” MUST be integer, hence, nPtr is automatically a memory address. In both cases, the address &number is brought into the function via the variable nPtr, that is, nPtr<–&number. I’m not sure which interpretation is better?

Categories: Uncategorized Tags: ,