volatile unsigned int x; // Global variable. All threads can change the value between [100, 1000]
void print()
{
for (int i = 0; i != x; i++)
cout<<i<<" ";
}
// I understand that print() function is potentially infinite
void print2()
{
int x2 = x;
for (int i = 0; i != x2; i++)
cout<<i<<" ";
}
// Now the question: Is it guaranteed that compiler won't optimize the x2 variable away. So is this print2() function safe?
Question about volatile
Moderator: Ras
-
Gian-Carlo Pascutto
- Posts: 1260
- Joined: Sat Dec 13, 2008 7:00 pm
Re: Question about volatile
The function is safe in the sense that it won't be infinite. But it's almost guaranteed x2 will be optimized away and put in a register - I think your question doesn't ask what you intended to.
-
Sven
- Posts: 4052
- Joined: Thu May 15, 2008 9:57 pm
- Location: Berlin, Germany
- Full name: Sven Schüle
Re: Question about volatile
Putting x2 into a register is not "optimizing away" since the register value won't change anymore in this case. I think Joona meant that print2() could be made equal to print() by an optimizer, causing the volatile x to be read once per iteration. But that should never happen, although I don't think the C or C++ standards do really _guarantee_ that. As far as I know the standards only "encourage" compilers not to optimize away access to volatiles.Gian-Carlo Pascutto wrote:The function is safe in the sense that it won't be infinite. But it's almost guaranteed x2 will be optimized away and put in a register - I think your question doesn't ask what you intended to.
Sven
-
Gian-Carlo Pascutto
- Posts: 1260
- Joined: Sat Dec 13, 2008 7:00 pm
Re: Question about volatile
There is no variable on the stack any more. What else is this than "optimized away"?Putting x2 into a register is not "optimizing away" since the register value won't change anymore in this case.
It turns out that the mere existence of the variable has little to do with the functioning of the program, which is why I indicated to the original poster that his question didn't make a lot of sense. What matters is how many times and when the memory is read.
Regardless of whether the variable physically exists or not, the memory read will only happen once, and that is what is critical.
No, in this case it does actually guarantee that the memory access happens right there. The volatile read is required to be done before the next sequence point, which in this case is the ; in the statement.As far as I know the standards only "encourage" compilers not to optimize away access to volatiles.
I'd personally consider it much better style not to use "volatile" at all but simply place a memory barrier after the read.
-
zamar
- Posts: 613
- Joined: Sun Jan 18, 2009 7:03 am
Re: Question about volatile
Thanks for the answer. I expected this but just wanted to be 100% sureGian-Carlo Pascutto wrote:The function is safe in the sense that it won't be infinite.
Joona Kiiski