+ 1

Uninitialized integer variable

#include <iostream> using namespace std; #define SquareOf(x) x * x   int main() {                 int x;                 cout<< SquareOf(x + 4);                 return 0; } Output of above code is 16.. I was expecting garbage value as it's uninitialized variable .. any thoughts!?

4th Jun 2018, 11:36 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Respuestas
+ 2
It's not unsigned, it's uninitialized. And there's nothing special about it. In fact, the majority of the memory the OS gives you will probably be filled with 0s for security reasons. You can see this by doing something like: int *p = new unsigned char[1024]; for (int i = 0; i<1024;++i) cout << reinterpret_cast<short>(p[i] << ' ');
4th Jun 2018, 12:31 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
yes, it's uninitialized..Let me update in main question.... still don't it should have garbage value? whatever you have told is for array and I think array is initialized with default value
4th Jun 2018, 12:51 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
It is probably compiler dependent. Some will auto initialize variables with 0, some will throw garbage values.
4th Jun 2018, 1:34 PM
Jakub Stasiak
Jakub Stasiak - avatar
0
You’ll have whatever value is at the stack pointer - 4 bytes. It won’t necessarily be garbage, the whole stack is commonly initialized to a special byte value or zero
4th Jun 2018, 2:04 PM
aklex
aklex - avatar
0
Ketan Lalcheta An array isn't initialized with a default value. However, since memory is shared between programs, the OS cleans it so you can't figure out the data of the previous program that used that memory.
4th Jun 2018, 3:55 PM
Vlad Serbu
Vlad Serbu - avatar