I’m trying to get a better grasp on pointers. My class assignment was to create the function for the prototype void OpenFile(const char *fileName, ifstream &inFile).
void OpenFile(const char *fileName, ifstream &inFile)
{
inFile.open(FILENAME, ios_base::in);
if (!inFile.is_open()) {
cerr << "Could not open file " << fileName << "\n";
exit(EXIT_FAILURE);
}
else {
cout << "File Open successful";
}
}
//FILENAME is defined as: const char * const FILENAME = "file.txt";
// function is called in main with: OpenFile(FILENAME, inFile);
I guess what I don’t understand is the const char * and the & for the two arguments. I am guessing that the first argument is a const char * because that’s how the assignment defined FILENAME. But did I have to use a pointer in this case? Could I have just done
const char FILENAME = "file.txt";
and in my OpenFile to have the first parameter just take in a const char. And then again, why do I need a reference for the second parameter of my function? Definitely confused on when to use pointers and when to use references. Thanks!
First, let me say that your function looks a bit strange if you pass in a parameter fileName but then use FILENAME within and fileName is just used for error output. I guess this is not quite correct.
Second, to the const char* issue. char itself is just a char (character) and as such is only one single character. const char FILENAME = “file.txt” would thus not work. Instead you’d need an array of chars (const char FILENAME[] = …), or as it is done in C use a pointer to the memory location of the text, i.e. char*.
As you seem to use STL, it may be a good idea to just ditch char* and convert to std::string instead.
Third, pointer vs reference is often a matter of taste. At the end they both do the same and within the compiler they are in fact the same. The one difference in use is that you can not pass an empty (null) reference, but you can pass a null pointer. So the recommendation usually is to use references if you really need an object passed, and a pointer for anything that could be optional (in which case you must handle ptr == NULL). Also C strings being char* and other manually allocated memory are usually sent via pointer.