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>
usingnamespace 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 = newint;
}
catch(bad_alloc error) {
cout << "Allocation of p failed\n";
return 1;
}
*p = 100;
cout << *p;
delete p;
return 0;
}
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()".