{"id":3043,"date":"2024-05-10T11:35:11","date_gmt":"2024-05-10T11:35:11","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=3043"},"modified":"2024-05-10T11:35:11","modified_gmt":"2024-05-10T11:35:11","slug":"understanding-volatile-qualifier-in-c-set-2-examples","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/understanding-volatile-qualifier-in-c-set-2-examples\/","title":{"rendered":"Understanding \u201cVolatile\u201d Qualifier In C | Set 2 (Examples)"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><p>Table of Contents<\/p><nav><ul><li ><a href=\"#understanding-volatile-qualifier-in-c-set-2-examples\">Understanding \u201cVolatile\u201d Qualifier In C  Set 2 (Examples)<\/a><\/li><li ><a href=\"#1-global-variables-modified-by-an-interrupt-service-routine-outside-the-scope\">1) Global variables modified by an interrupt service routine outside the scope:<\/a><\/li><li ><a href=\"#2-global-variables-within-a-multi-threaded-application\">2) Global variables within a multi-threaded application:<\/a><\/li><li ><a href=\"#example-to-illustrate-the-compilers-interpret-volatile-keyword\">Example- To illustrate the compilers interpret volatile keyword<\/a><\/li><li ><a href=\"#compile-the-same-code-with-the-optimization-option-i-e-o-option\">Compile The Same code with the optimization option (i.e. -O option)<\/a><\/li><li ><a href=\"#faq-understanding-volatile-qualifier-in-c-set-2-examples\">FAQ- Understanding \u201cVolatile\u201d Qualifier In C | Set 2 (Examples)<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"understanding-volatile-qualifier-in-c-set-2-examples\">Understanding \u201cVolatile\u201d Qualifier In C  Set 2 (Examples)<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The &#8220;volatile&#8221; keyword is used to prevent the compiler from optimizing objects whose values can change unpredictably, usually due to external factors. When an object is declared as volatile, the compiler ensures that its value is always read from memory, even if it appears redundant, to avoid potential issues caused by optimizations. This is crucial for ensuring the correct behavior of objects that can change independently of the program&#8217;s logic.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-global-variables-modified-by-an-interrupt-service-routine-outside-the-scope\">1) Global variables modified by an interrupt service routine outside the scope:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"> Global variables modified by an interrupt service routine (ISR) often require the &#8220;volatile&#8221; keyword. For instance, when dealing with data ports, declaring a variable as &#8220;volatile&#8221; ensures that the compiler doesn&#8217;t optimize the code to read the port just once and cache the value. Instead, it forces the code to always fetch the latest data from the port. ISRs are typically used to update these variables when new data arrives due to interruptions, maintaining data accuracy in real-time applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-global-variables-within-a-multi-threaded-application\">2) Global variables within a multi-threaded application:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When multiple threads share information using global variables, it&#8217;s essential to mark these variables as &#8220;volatile.&#8221; This ensures that updates made by one thread are always freshly fetched by others. Without &#8220;volatile,&#8221; the compiler might optimize by caching the values, which can lead to synchronization issues in asynchronous thread execution. Using &#8220;volatile&#8221; nullifies these compiler optimizations, making global variables suitable for safe inter-thread communication.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If we do not use the volatile qualifier, the following problems may arise:&nbsp;<br>1) Code may not work as expected when optimization is turned on.&nbsp;<br>2) Code may not work as expected when interrupts are enabled and used.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"example-to-illustrate-the-compilers-interpret-volatile-keyword\">Example- To illustrate the compilers interpret volatile keyword<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In the program below, We are changing the value of a const object with the pointer and also compiling code without an optimization option.  Therefore, the compiler won\u2019t do any optimization and will change the value of the const object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n\n\/* Compile code without optimization option *\/\n#include &lt;stdio.h&gt;\nint main(void)\n{\n    const int local = 10;\n    int *ptr = (int*) &amp;local;\n \n    printf(\"Initial value of local : %d \\n\", local);\n \n    *ptr = 100;\n \n    printf(\"Modified value of local: %d \\n\", local);\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Preprocessed Code<\/strong>: This file has the &#8220;.i&#8221; extension and contains the code after preprocessing, which includes macro expansions, file inclusions, and other preprocessing directives. It&#8217;s often a human-readable form of the code that&#8217;s processed by the compiler.<\/li>\n\n\n\n<li><strong>Assembly Code<\/strong>: The assembly code file has the &#8220;.s&#8221; extension and contains the code translated into assembly language. This code is closer to the low-level machine instructions and is often specific to the target architecture for which the code is being compiled.<\/li>\n\n\n\n<li><strong>Object Code<\/strong>: The object code file has the &#8220;.o&#8221; extension and contains the code in a binary format that is not human-readable. It&#8217;s generated after the compilation and assembly stages and is ready to be linked into an executable program.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> &#91;narendra@ubuntu]$ gcc volatile.c -o volatile \u2013save-temps\n  &#91;narendra@ubuntu]$ .\/volatile\n  Initial value of local : 10\n  Modified value of local: 100\n  &#91;narendra@ubuntu]$ ls -l volatile.s\n  -rw-r\u2013r\u2013 1 narendra narendra 731 2016-11-19 16:19 volatile.s\n  &#91;narendra@ubuntu]$<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"compile-the-same-code-with-the-optimization-option-i-e-o-option\">Compile The Same code with the optimization option (i.e. -O option)<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In the given code, there&#8217;s a variable called &#8220;local&#8221; that&#8217;s marked as &#8220;const,&#8221; which means it can&#8217;t be changed after it&#8217;s set. The GCC compiler is smart and doesn&#8217;t execute any instructions that try to change the value of this &#8220;const&#8221; variable. So, the value of the &#8220;const&#8221; variable stays the same throughout the program.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/* Compile code with optimization option *\/\n#include &lt;stdio.h&gt;\n \nint main(void)\n{\n    const int local = 10;\n    int *ptr = (int*) &amp;local;\n \n    printf(\"Initial value of local : %d \\n\", local);\n \n    *ptr = 100;\n \n    printf(\"Modified value of local: %d \\n\", local);\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  &#91;narendra@ubuntu]$ gcc -O3 volatile.c -o volatile \u2013save-temps\n  &#91;narendra@ubuntu]$ .\/volatile\n  Initial value of local : 10\n  Modified value of local: 10\n  &#91;narendra@ubuntu]$ ls -l volatile.s\n  -rw-r\u2013r\u2013 1 narendra narendra 626 2016-11-19 16:21 volatile.s<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When a variable is declared as both <code>const<\/code> and <code>volatile<\/code>, it indicates to the compiler that the value of the variable can change at any time due to external factors and, therefore, should not be subject to optimizations. Even when you compile the code with optimization options, the value of the <code>const<\/code> and volatile object can change because the volatile qualifier instructs the compiler not to perform any optimizations that might prevent or alter changes to the variable. This combination is useful when you want to ensure that a variable remains accessible and up-to-date in situations where the value can change unexpectedly, even in optimized code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n\/* Compile code with optimization option *\/\n#include &lt;stdio.h&gt;\n \nint main(void)\n{\n    const volatile int local = 10;\n    int *ptr = (int*) &amp;local;\n \n    printf(\"Initial value of local : %d \\n\", local);\n \n    *ptr = 100;\n \n    printf(\"Modified value of local: %d \\n\", local);\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;narendra@ubuntu]$ gcc -O3 volatile.c -o volatile \u2013save-temp\n  &#91;narendra@ubuntu]$ .\/volatile\n  Initial value of local : 10\n  Modified value of local: 100\n  &#91;narendra@ubuntu]$ ls -l volatile.s\n  -rw-r\u2013r\u2013 1 narendra narendra 711 2016-11-19 16:22 volatile.s\n  &#91;narendra@ubuntu]$<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Think of the touch sensor on a mobile phone. The software that handles the touch sensor should do two things:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>It should promise not to change the location where you touch, ensuring the data&#8217;s integrity. That&#8217;s the &#8220;const&#8221; part.<\/li>\n\n\n\n<li>It should always read the touch input as if it&#8217;s brand new, as touch data changes all the time. This is the &#8220;volatile&#8221; part.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">So, for the touch sensor driver, it&#8217;s crucial to handle touch data in a &#8220;const volatile&#8221; manner, which guarantees accuracy and responsiveness to changing touch inputs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-understanding-volatile-qualifier-in-c-set-2-examples\">FAQ- Understanding \u201cVolatile\u201d Qualifier In C | Set 2 (Examples)<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1698235891010\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. <strong>What is a volatile qualifier in C?<\/strong><\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. &#8220;Volatile&#8221; is a label you can give to a variable when you declare it. It tells the compiler that the variable&#8217;s value might change at any time without the program&#8217;s knowledge or control. This means the compiler should be cautious about optimizing or caching the variable, as it can change unexpectedly.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1698235902165\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2. What is the use of volatile in the C example?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. Example. The code snippet below is of using &#8216;volatile&#8217;  used to declare a variable in C:\u00a0volatile int *p = (volatile int *) 0x1000; \/\/ declare a volatile pointer to an address in memory.\u00a0volatile int x = 0; \/\/ declare a volatile integer variable.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1698235910600\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. What are volatile type qualifiers?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. The &#8220;volatile&#8221; qualifier is used to declare a data object that can have its value changed in ways that are beyond the control or detection of the compiler. This includes situations where a variable&#8217;s value may be updated by external factors like the system clock or another program.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Understanding \u201cVolatile\u201d Qualifier In C Set 2 (Examples) The &#8220;volatile&#8221; keyword is used to prevent the compiler from optimizing objects whose values can change unpredictably, usually due to external factors. When an object is declared as volatile, the compiler ensures that its value is always read from memory, even if it appears redundant, to avoid &#8230; <a title=\"Understanding \u201cVolatile\u201d Qualifier In C | Set 2 (Examples)\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/understanding-volatile-qualifier-in-c-set-2-examples\/\" aria-label=\"More on Understanding \u201cVolatile\u201d Qualifier In C | Set 2 (Examples)\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":3044,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[503],"class_list":["post-3043","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-understanding-volatile-qualifier-in-c-set-2-examples","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3043","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=3043"}],"version-history":[{"count":10,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3043\/revisions"}],"predecessor-version":[{"id":10743,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3043\/revisions\/10743"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/3044"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=3043"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=3043"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=3043"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}