English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Then how come the program given below runs properly even when we have not initialized p?

#include
void main( )
{
const char *p ;
p = "A const pointer" ;
cout << p ;
}

2007-09-14 05:15:45 · 3 answers · asked by zalai t 1 in Computers & Internet Programming & Design

3 answers

I'd guess that since p has already been defined somewhere before this code, that the pointer to p (*p) already has a valid address, effectively it has already been initialized.

2007-09-14 05:21:10 · answer #1 · answered by Anonymous · 0 0

Because the hardcoded string "A const pointer" is of type const char*.

It has nothing to do with the address. It has to do with the data that p is pointing to. The data is what is const, not p.

2007-09-14 08:16:24 · answer #2 · answered by Daniel H 5 · 0 0

A few things The first thing - it's your choice, but for me, it makes sense to have the functions declared BEFORE int main(). Like this: //Declare function for outputting age. int showAge(int age) { while(a... } //Declare function for error checking. int ageCheck(int check) { while( .... } int main() { //Declare needed variables. const int LOW = 1; ... } This eliminates the need for void showAge(int); void ageCheck(int); Also you need const int LOW = 1; const int HIGH = 100; outside of int main. The functions are outside of int main, so they can't access them. Why do you have while loops in your functions? If statements would be much better as they won't return an endless stream of " You are __ years old." '0' and '9' shouldn't be in single quotes. age is an int, not a char or string. Why are showAge and ageCheck ints? They don't return anything. They should be void showAge(int age) and void ageCheck(int AGE). As you see, I changed int check to int age. You are using age in the function ageCheck, not check, so change one. I missed a bunch probably, so this is what I changed the code to: #include #include using namespace std; const int LOW = 1; const int HIGH = 100; //Declare function for outputting age. int showAge(int age) { if(age >= LOW && age <= HIGH) { cout << "You are " << age << " years old!" << endl; } } //Declare function for error checking. int ageCheck(int age) { if(age <= LOW || age >= HIGH) { cout << " " < 9) { cout << "Please enter a valid age from 1 through 100: "; cin >> age; ageCheck(age); } else { showAge(age); } } int main() { //Declare needed variables. int age; //Get age from the user. cout << "Please enter your age from 1 through 100: "; cin >> age; showAge(age); ageCheck(age); return 0; }

2016-05-19 04:28:35 · answer #3 · answered by ? 3 · 0 0

fedest.com, questions and answers