I am trying to learn C++ on my own using the "Teach Yourself C++ in 24 hours" by Jesse Liberty. I wrote this short program to figure out pointers in C++.
#include <iostream>
void hMany(int count); // hMany function prototype
void hMany(int count){
do {
std::cout << "Hello...\n";
count--;
} while (count >0 );
};
int main (int argc, const char * argv[]) {
int counter;
int * pCounter = &counter;
std::cout << "How many hellos? ";
std::cin >> counter;
hMany(*pCounter);
std::cout << "counter is: " << counter << std::endl;
std::cout << "*pCounter is: " << *pCounter << std::endl;
return 0;
}
The resulting output is:
How many hellos? 2
Hello...
Hello...
counter is: 2
*pCounter is: 2
What is the benefit of passing the pointers (*pCounter) vs the argument (counter)?
Any help would be greatly appreciated. Luis
Update:
Ok. The program is working and I now fully understand the C++ pointers. Thank you all for your responses. After trying Chowlett's code I was getting 2 warnings (not errors). One was ! No previous prototype for function hMany and *pCount-- ! Expression result unused. I was able to correct the prototype on my own but I couldn't figure out the *pCount-- warning.
I asked my friend Tony for help and here is his answer.
The parentheses make things happen in the correct order.
(*pCount)--
says to follow the pointer to the integer it points to, and then decrement the integer, which is what you want to do.
*pCount--
ends up doing the wrong thing, the compiler treats it as
*(pCount—)
which says to decrement the pointer first, leaving it pointing to the “integer” before the one you want to change (there is no such thing since you only have one integer you called this function with), then follow this decremented pointer and do nothing with the integer at that memory location. This is why the compiler complained that the expression result was unused. The compiler was correct. This code decrements the pointer incorrectly, fetches the wrong integer, and doesn’t store that wrong integer anywhere.
Here's the correct code for those new to C++ who might be interested.
include
void hMany(int *pCount); // hMany function prototype
void hMany(int *pCount){ // *pCount receiving the address of count
do {
std::cout << "Hello...\n";
// The parentheses make things happen in the correct order.
// says to follow the pointer to the integer it points to,
// and then decrement the integer.
(*pCount)--;
} while (*pCount >0 );
}
int main (int argc, const char * argv[]) {
int counter;
int * pCounter = &counter;
std::cout << "How many hellos? ";
std::cin >> counter;
hMany(pCounter); // passing the address of counter
std::cout << "counter is: " << counter << std::endl;
std::cout << "*pCounter is: " << *pCounter << std::endl;
return 0;
}