{"id":1963,"date":"2024-05-10T06:55:24","date_gmt":"2024-05-10T06:55:24","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=1963"},"modified":"2024-05-10T06:55:24","modified_gmt":"2024-05-10T06:55:24","slug":"different-ways-to-declare-variable-as-constant-in-c-and-c","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/different-ways-to-declare-variable-as-constant-in-c-and-c\/","title":{"rendered":"Different Ways To Declare Variable As Constant In C And C++"},"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=\"#different-ways-to-declare-variable-as-constant-in-c-and-c\">Different Ways To Declare Variable As Constant In C And C++<\/a><\/li><li ><a href=\"#various-methods-to-declare-variable-constant\">Various Methods to Declare Variable Constant <\/a><\/li><li ><a href=\"#1-const-keyword\">1. Const keyword<\/a><\/li><li ><a href=\"#2-enum-keyword\">2. Enum keyword<\/a><\/li><li ><a href=\"#3-using-constexpr-keyword\">3. Using\u00a0constexpr\u00a0keyword<\/a><\/li><li ><a href=\"#4-using-macros\">4. Using\u00a0Macros<\/a><\/li><li ><a href=\"#faq-different-ways-to-declare-variable-as-constant-in-c-and-c\">FAQ- Different Ways To Declare Variable As Constant In C And C++<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"different-ways-to-declare-variable-as-constant-in-c-and-c\">Different Ways To Declare Variable As Constant In C And C++<\/h2>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"various-methods-to-declare-variable-constant\">Various Methods to Declare Variable Constant <\/h2>\n\n\n\n<p>There are various methods to make a variable constant.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-const-keyword\">1. Const keyword<\/h2>\n\n\n\n<p> One way is by using the <code>const<\/code> keyword. When you declare a variable with <code>const<\/code>, it means that its value cannot be changed once it&#8217;s set, and this is determined at compile time.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to demonstrate const specifier\n#include &lt;stdio.h&gt;\nint main()\n{\n    const int num = 1;\n  \n    num = 5; \/\/ Modifying the value\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>When you declare a variable as <code>const<\/code> and then try to change its value, the compiler will generate an error similar to the one you mentioned: &#8220;error: assignment of read-only variable &#8216;num&#8217;.&#8221; This error is a safeguard to ensure that you don&#8217;t accidentally modify a constant variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-enum-keyword\">2. Enum keyword<\/h2>\n\n\n\n<p><strong>The enum keyword<\/strong>:  is used to define an enumeration in C and C++. Enumerations allow you to assign names or labels to integral constants, making the code more readable and maintainable. Here&#8217;s an example of how you might use <code>enum<\/code> in C++:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ In C and C++ internally the default\n\/\/ type of 'var' is int\nenum VARS { var = 42 };\n  \n\/\/ In C++ 11 (can have any integral type):\nenum : type { var = 42; }\n  \n\/\/ where mytype = int, char, long etc.\n\/\/ but it can't be float, double or\n\/\/ user defined data type<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-using-constexpr-keyword\">3. Using&nbsp;constexpr&nbsp;keyword<\/h2>\n\n\n\n<p> In C++, the constexpr keyword is used to declare variables as guaranteed constants. When you declare a variable, it must be initialized with a constant expression. This means that the value must be computable at compile time, not runtime. If the initializer of a <code>constexpr<\/code> variable isn&#8217;t a constant expression, the code will fail to compile. This helps ensure that <code>constexpr<\/code> variables are indeed constants that can be determined at compile time for optimization purposes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n  \nint main()\n{\n    int var = 5;\n    constexpr int k = var;\n    std::cout &lt;&lt; k;\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>If you attempt to initialize a <code>constexpr<\/code> variable with a value that cannot be determined at compile time, you will receive an error message like the one you mentioned: &#8220;error: the value of &#8216;var&#8217; is not usable in a constant expression.&#8221; This is a compiler error designed to enforce the rule that <code>constexpr<\/code> variables must be initialized with constant expressions.<\/p>\n\n\n\n<p>If you want a variable to be a true constant, which means its value cannot be changed after initialization, you should declare it using the <code>const<\/code> keyword.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-using-macros\">4. Using&nbsp;Macros<\/h2>\n\n\n\n<p>Macros can be used to define constants in C and C++. However, there are some important considerations and potential issues when using macros for constants.<\/p>\n\n\n\n<p>Macros in C and C++ are handled by the preprocessor, and they perform simple text replacement in your source code before it&#8217;s compiled. This text-based substitution means that macros lack type checking, and they can indeed be redefined or changed throughout your codebase, leading to potential errors and unexpected behavior.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C++ program to demonstrate the problems\n\/\/ in 'Macros'\n#include &lt;iostream&gt;\nusing namespace std;\n  \n#define var 5\nint main() {\n    printf(\"%d \", var);\n  \n    #ifdef var\n    #undef var\n  \n    \/\/ redefine var as 10\n    #define var 10\n    #endif\n  \n    printf(\"%d\", var);\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>Output:<\/strong> 5 10<\/code><\/pre>\n\n\n\n<p><strong>Note :<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Preprocessor Macros:<\/strong> Preprocessor macros are essentially text replacements and are suitable for defining literal constants. They are not associated with any specific data type or memory location. They are primarily used for simple text substitution and should be avoided for more complex constant requirements.<\/li>\n\n\n\n<li><strong>Enums:<\/strong> Enums provide symbolic names for integral constants and are suitable for defining integer constants. Enums do not have specific memory addresses and are typically used for making code more readable and maintainable.<\/li>\n\n\n\n<li><strong><code>const<\/code> and <code>constexpr<\/code>:<\/strong> <code>const<\/code> and <code>constexpr<\/code> are used to define true constants with specific memory addresses. They provide type safety and are the recommended way to define constants when you need them to have a particular data type and memory location. <code>const<\/code> is used for runtime constants, while <code>constexpr<\/code> is used for compile-time constants.<\/li>\n<\/ol>\n\n\n\n<p>In practice, <code>const<\/code> and <code>constexpr<\/code> are preferred for defining constants when you need type safety, memory control, and more versatile constant values. Preprocessor macros and enums have their use cases but may not offer the same level of control and safety as <code>const<\/code> and <code>constexpr<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-different-ways-to-declare-variable-as-constant-in-c-and-c\">FAQ- Different Ways To Declare Variable As Constant In C And C++<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1695113675541\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. How variable declaration in C is different from C++?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. In C, variables must be declared at the beginning of a scope, leading to less readable code. In C++, variables can be declared anywhere in the scope, making the code more intuitive and easier to understand.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1695113722628\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2.What is a declaration statement in C++?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. In C++, a declaration gives a unique name to something and specifies its type and properties. The moment a name is declared is when it becomes known to the compiler.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1695113825370\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. What is a variable declaration and initialization in C++?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans.A declaration informs the compiler about an entity&#8217;s presence in the program and where it&#8217;s located. When you declare a variable, it&#8217;s a good practice to also initialize it, which means assigning an initial value to the variable.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Different Ways To Declare Variable As Constant In C And C++ Various Methods to Declare Variable Constant There are various methods to make a variable constant. 1. Const keyword One way is by using the const keyword. When you declare a variable with const, it means that its value cannot be changed once it&#8217;s set, &#8230; <a title=\"Different Ways To Declare Variable As Constant In C And C++\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/different-ways-to-declare-variable-as-constant-in-c-and-c\/\" aria-label=\"More on Different Ways To Declare Variable As Constant In C And C++\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":1964,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[28,27],"tags":[333],"class_list":["post-1963","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp-programming","category-c-programming","tag-different-ways-to-declare-variable-as-constant-in-c-and-c","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\/1963","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=1963"}],"version-history":[{"count":11,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/1963\/revisions"}],"predecessor-version":[{"id":10615,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/1963\/revisions\/10615"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/1964"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=1963"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=1963"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=1963"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}