Mohammad Ghanatian Mohammad Ghanatian - 7 months ago 47
C++ Question

Pointer with no initialization in Visual studio 2015 and in c++ language

Consider this simple code:

#include "stdafx.h"
using namespace std;

int main()
void* voidptr;
cout << voidptr << endl;


Here is the error:The error

When I run this in visual studio 2015 I get a Debug error but when I do this in code blocks the program works with no error.I read in my textbook that we can use a pointer without initialization but now I can't do it in visual studio.
Does anybody know that what the problem is?

Here is my textbook:Object-oriented programming in c++ by Roabert Lafore


When you compile this program, the compiler warns you that voidptr is used without having been initiaslized in this line: `cout << voidptr << endl;

When you run this program you get this error:

enter image description here

Which again tells you that voidptris being used without beiing initialized. This can hardly be clearer.

In C and C++ local variables are not initialized, they contain what ever value has been in memory before, the values are undeterminate. Now when you run the debug version of a program, you get this debug message, because the compiler is kind enough to show you that you are using an uninitialized variable.

Try to run the release version of the program, you won't get any more error, but some apparently random value will be displayed.