Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the address of this volatile variable always at 1?

Tags:

I wanted to inspect the address of my variable

volatile int clock; cout << &clock; 

But it always says that x is at address 1. Am i doing something wrong??

like image 878
Johannes Schaub - litb Avatar asked Nov 23 '11 08:11

Johannes Schaub - litb


People also ask

What happens when a variable is declared volatile?

Volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby.

How is the value of volatile variables altered?

The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.

What is volatile variable in C with example?

The volatile qualifier is applied to a variable when we declare it. It is used to tell the compiler, that the value may change at any time. These are some properties of volatile. It cannot cache the variables in register.

Where the volatile variables are stored in memory?

There's no reason for a volatile variable to be stored in any "special" section of memory. It is normally stored together with any other variables, including non-volatile ones. If some compiler decides to store volatile variables in some special section of memory - there's nothing to prevent it from doing so.


2 Answers

iostreams will cast most pointers to void * for display - but no conversion exists for volatile pointers. As such C++ falls back to the implicit cast to bool. Cast to void* explicitly if you want to print the address:

std::cout << (void*)&clock; 
like image 100
bdonlan Avatar answered Sep 22 '22 06:09

bdonlan


There's an operator<< for const void*, but there's no operator<< for volatile void*, and the implicit conversion will not remove volatile (it won't remove const either).

As GMan says, the cv-qualification of the type pointed to should be irrelevant to the business of printing an address. Perhaps the overload defined in 27.7.3.6.2 should be operator<<(const volatile void* val);, I can't immediately see any disadvantage. But it isn't.

#include <iostream>  void foo(const void *a) {     std::cout << "pointer\n"; }  void foo(bool a) {     std::cout << "bool\n"; }  int main() {     volatile int x;     foo(&x);     std::cout << &x << "\n";     int y;     foo(&y);     std::cout << &y << "\n";     void foo(volatile void*);     foo(&x); }  void foo(volatile void *a) {     std::cout << "now it's a pointer\n"; } 

Output:

bool 1 pointer 0x22cd28 now it's a pointer 
like image 32
Steve Jessop Avatar answered Sep 26 '22 06:09

Steve Jessop