A
Allan Bruce
Hi there,
I mainly use c for programming but have decided to try and learn c++.
I found a text which delcares the following
{
int *variablePointer;
int count = 32;
variablePointer = &count;
cout << *variablePointer;
}
This I understand as it is very similar in c. My belief is that
variablePointer is a pointer to an int. count is declared as an int and
initialised to 32. variablePointer is then set to point to count, and
therefore has value 32 when cout is called.
My problem is then in the following example which is supposedly wrong:
{
int *variablePointer;
{
int count = 32;
variablePointer = &count;
}
cout << *variablePointer;
}
I just want to clarigy if I understand why this is wrong.
variablePointer again is a pointer to an int and has scope within the
whole of the above function. We then enter a new scope sub-level, and
count is decalred as an int and initialised to the value of 32.
variablePointer is set to point to count. We then leave this scope
level, and when we try to use cout for variablePointer, we are causing
undefined behaviour. Is this a correct assumption?
Thanks
Allan
I mainly use c for programming but have decided to try and learn c++.
I found a text which delcares the following
{
int *variablePointer;
int count = 32;
variablePointer = &count;
cout << *variablePointer;
}
This I understand as it is very similar in c. My belief is that
variablePointer is a pointer to an int. count is declared as an int and
initialised to 32. variablePointer is then set to point to count, and
therefore has value 32 when cout is called.
My problem is then in the following example which is supposedly wrong:
{
int *variablePointer;
{
int count = 32;
variablePointer = &count;
}
cout << *variablePointer;
}
I just want to clarigy if I understand why this is wrong.
variablePointer again is a pointer to an int and has scope within the
whole of the above function. We then enter a new scope sub-level, and
count is decalred as an int and initialised to the value of 32.
variablePointer is set to point to count. We then leave this scope
level, and when we try to use cout for variablePointer, we are causing
undefined behaviour. Is this a correct assumption?
Thanks
Allan