27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 13 | C++<br />

13.5 What is <strong>the</strong> significance of <strong>the</strong> keyword “volatile” in C?<br />

pg 76<br />

SOLUTION<br />

Volatile informs <strong>the</strong> compiler that <strong>the</strong> value of <strong>the</strong> variable can change from <strong>the</strong> outside,<br />

without any update done by <strong>the</strong> code.<br />

Declaring a simple volatile variable:<br />

volatile int x;<br />

int volatile x;<br />

Declaring a pointer variable for a volatile memory (only <strong>the</strong> pointer address is volatile):<br />

volatile int * x;<br />

int volatile * x;<br />

Declaring a volatile pointer variable for a non-volatile memory (only memory contained is<br />

volatile):<br />

int * volatile x;<br />

Declaring a volatile variable pointer for a volatile memory (both pointer address <strong>and</strong> memory<br />

contained are volatile):<br />

volatile int * volatile x;<br />

int volatile * volatile x;<br />

Volatile variables are not optimized, but this can actually be useful. Imagine this function:<br />

1 int opt = 1;<br />

2 void Fn(void) {<br />

3 start:<br />

4 if (opt == 1) goto start;<br />

5 else break;<br />

6 }<br />

At first glance, our code appears to loop infinitely. The compiler will try to optimize it to:<br />

1 void Fn(void) {<br />

2 start:<br />

3 int opt = 1;<br />

4 if (true)<br />

5 goto start;<br />

6 }<br />

This becomes an infinite loop. However, an external program might write ‘0’ to <strong>the</strong> location<br />

of variable opt. Volatile variables are also useful when multi-threaded programs have global<br />

variables <strong>and</strong> any thread can modify <strong>the</strong>se shared variables. Of course, we don’t want optimization<br />

on <strong>the</strong>m.<br />

2 1 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Knowledge Based

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!