- August 12, 2014 at 12:07 pm #31785
I am working in linux environment
I am trying to declare a global variable, and that global variable is allocated in memory..
But i want to initialize that global variable while declaring itself, and i tried, that variable is being allocated,but it was not initialized with the value provided.
How can i initialize the global variable while declaring itself.
help me out.
I tried in this way..
volatile int x =10;
x variable= undefined value (‘X’)
y variable = undefined value (‘X’)
when I try to write the “x” variable value into the memory location, i cannot see the value “10” .
Do I need to take an extra care while initializing the global variables while declaring itself.
IF I initialize the global variable in any one of the functions it is working properly.
volatile int x ;
x variable =15;
y variable =15;
Thanks in advance. 🙂October 20, 2014 at 3:37 pm #38922
Firstly, are you sure you want the variable to be global? Global variables are bad in general and can usually be avoided. If you really need it in this file then consider the use of static instead but I’d avoid that too if at all possible.
Alternatively, you could declare it extern in the header and define it in the file as a global, though not volatile. Why do you want it to be volatile anyhow; this is not clear.
Secondly, I don’t think the fact that you are using Linux is particularly relevant; it’s the language use you should be worried about.
I recommend taking a look at http://en.wikipedia.org/wiki/Volatile_variable.
In particular, note that
“Operations on volatile variables are not atomic, nor do they establish a proper happens-before relationship for threading. This is according to the relevant standards (C, C++, POSIX, WIN32), and this is the matter of fact for the vast majority of current implementations. Thus, the usage of volatile keyword as a portable synchronization mechanism is discouraged by many C/C++ groups.”
If you are working in a multithreaded environment then consider declaring a variable and changing it using a synchronisation mechanism rather than using the volatile keyword. Mutexes might be an alternative you could use in linux for this.