Does volatile variable have allocated memory? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Does volatile variable have allocated memory?

```cpp volatile int var = 10; std::cout << &var;//prints 1 ``` I think it doesn't allocated memory. But why it print 1?

10th Mar 2019, 3:32 PM
RainStorm
RainStorm - avatar
1 Answer
+ 3
It does allocate memory. Normally when iostream prints the address of a variable it converts it to a void* and then calls the operator<< overload that prints void*. However no such overload exists for volatile void* and iostream's next best option is to convert it to a bool, which explains why it prints a 1. The same thing happens to function pointers. If you want to print the address of a volatile variable you can either cast it to void* yourself: std::cout << (void*)&var; or overload the operator<< volatile void* for iostream. std::ostream& operator<<( std::ostream& os, const volatile void* p ) { return os << (void*)p; } ... std::cout << &var;
10th Mar 2019, 5:38 PM
Dennis
Dennis - avatar