What's wrong with this?

Hey guys, before I start harassing you about my C++ problems, just wanna say
HAPPY NEW YEAR(!) to everyone:P. Now to get to the point..

What's troubling me, is this short code shown below. Compiler gives me undeclared indetifier 'p' error in line 15,16,17(+ cannot delete object that is not pointer, which is related...) If it's of any importance I use Visual Studio 2008.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <new>
using namespace std;

int main () {
	/* int*p;  If I put it here, it compiles ok*/ 
	try {
		int *p; //But if I put the decleration of *p here...
		p = new int;
	}
	catch(bad_alloc error) {
		cout << "Allocation of p failed\n";
		return 1;
	}
	*p = 100;
	cout << *p;
	delete p;
	return 0;
}


Please help =) !



Last edited on
Is it maybe prohibited to declare pointers inside try?
Last edited on
The scope of variables and objects is limited to the block they appear in.
1
2
3
4
5
6
7
8
9
10
11
12
{
    int a;
    a=4; //OK
}
a=4; //Error. a went out of scope on the previous line.
{
    int a=4;
    {
        int a=5;
    }
    std::cout <<a<<std::endl;
}
Last edited on
When you declare a variable inside a block, it is only available within THAT block (or subsequent blocks within that block). By declaring "p" inside the "try" block, you are declaring it locally. When that block of code ends, the variable "p" is automatically destroyed, and goes out of scope.

When you declare it in "main()", then it is available to the entire "main() {}" block. Therefore it is still available for you to change later. It only gets destroyed at the end of "main()".

Last edited on
Ahhh of course, p goes out of scope! I'm so busy learning new things that I forget the basics... Thanks helios and jrohde
Last edited on
Topic archived. No new replies allowed.