{"id":81411,"date":"2021-07-08T09:00:41","date_gmt":"2021-07-08T03:30:41","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81411"},"modified":"2021-07-08T09:00:41","modified_gmt":"2021-07-08T03:30:41","slug":"variables-in-cpp","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/","title":{"rendered":"Variables in C++"},"content":{"rendered":"<p>In this article, we will learn about variables in C++.<\/p>\n<p>In a program, the basic unit of storage is a variable. It is a name given to a location in memory that stores some data.<br \/>\nWhile program execution, we can change the value stored in a variable.<\/p>\n<h3>Naming a Variable in C++<\/h3>\n<p>There are some rules to name a variable in C++<\/p>\n<ul>\n<li>We can start a variable name with an alphabet or an underscore but not with a digit<\/li>\n<li>Variables are case sensitive in C++<\/li>\n<li>We must not include any special character, symbol or whitespaces in a variable name<\/li>\n<li>Within a scope, all variables should have unique names<\/li>\n<li>We cannot use a keyword as a variable name.<\/li>\n<\/ul>\n<p><strong>For example,<\/strong><\/p>\n<p>Some valid variable names are age, _city, student_name, str, etc.<\/p>\n<p>Some invalid variable names are 5age, student name, student@name, string, etc.<\/p>\n<h3>Variable Definition and Declaration in C++<\/h3>\n<p>We must know that there is a difference between declaring a variable and defining it. When we declare a variable, we introduce it to the compiler before its use. Whereas, defining a variable means when memory is allocated and a value is assigned to it in the program.<\/p>\n<p>Usually, both declaration and definition are done together.<\/p>\n<p>Let\u2019s declare and define a variable in C++,<br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">data_type variable_name;<\/pre>\n<p>Here, data_type specifies the size and type of data a variable can store.<\/p>\n<p>If we want multiple variables of same data type, we can define them as<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">data_type variable_name1, variable_name2, variable_name3;<\/pre>\n<p>Let\u2019s see some examples,<\/p>\n<p>int age; \/\/a variable named age and type integer<\/p>\n<p>char answer; \/\/a variable named answer and type character<\/p>\n<p>In these examples, variables age and answer are assigned some garbage value.<\/p>\n<h3>Variable Initialization in C++<\/h3>\n<p>When we assign some initial value to a variable, it is called variable initialization.<\/p>\n<p>Syntax for declaring and initializing a variable in the same line:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">data_type variable_name = value;<\/pre>\n<p><strong>For example,<\/strong><\/p>\n<p>int age = 10;<\/p>\n<p>We can initialize an already declared variable age as<br \/>\nage = 10;<\/p>\n<h3>Variable Scope in C++<\/h3>\n<p>The scope of a variable in programming is the range of visibility, out of which the variable cannot be accessed.<\/p>\n<p>Variables declared inside main() in C++ cannot be accessed from outside it. A variable&#8217;s scope is confined to the curly braces that contain it; attempting to access it from outside will result in a compilation error.<\/p>\n<p>Variables in C++ can be one of two types, depending on their scope:<\/p>\n<h4>1. Local Variables in C++<\/h4>\n<p>Local variables are variables that are declared within a function or code block. They can only be used by statements that are included within that function or block. They do not exist outside that function or block.<\/p>\n<h4>Initializing Local Variables<\/h4>\n<p>When we define a local variable, we need to initialize it. The system does not auto initialize it.<\/p>\n<p><strong>Example of local variables in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nvoid fun() {\n    int total = 100;    \/\/Local to fun()\n    cout&lt;&lt;total;\n}\nint main() {\n  cout&lt;&lt;\"Total = \"&lt;&lt;total;    \n  return 0;\n}\n<\/pre>\n<p><strong>Status<\/strong> Compilation error<br \/>\n<strong>Output<\/strong><\/p>\n<div class=\"code-output\">In function \u2018int main()\u2019:<br \/>\nerror: \u2018total\u2019 was not declared in this scope<\/div>\n<p><strong>Corrected Program<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nvoid fun() {\n    int total = 100;    \/\/Local to fun()\n    cout&lt;&lt;total;\n}\nint main() {\n  cout&lt;&lt;\"Total = \";\n  fun();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Total = 100<\/div>\n<h4>2. Global Variables in C++<\/h4>\n<p>Global variables are accessible from anywhere in the program. These are available until the lifetime of the program ends. These variables are normally defined at the top, outside all functions and blocks.<\/p>\n<h4>Initializing Global Variables<\/h4>\n<p>While defining a global variable if we do not assign any value to it, it is initialized by the system automatically. The values assigned are:<\/p>\n<table style=\"height: 143px\" width=\"623\">\n<tbody>\n<tr>\n<td><b>Data Type<\/b><\/td>\n<td><b>Initializer<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">int<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">char<\/span><\/td>\n<td><span style=\"font-weight: 400\">&#8216;\\0&#8217;<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Example of global variables in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint g = 15;     \/\/global variable\n\nint main() {\n  cout&lt;&lt;\"Value of global variable = \"&lt;&lt;g&lt;&lt;endl;\n  g*=2;\n  cout&lt;&lt;\"Modified value of global variable = \"&lt;&lt;g;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Value of global variable = 15<br \/>\nModified value of global variable = 30<\/div>\n<h3>When a Local and a Global variable have same name<\/h3>\n<p><strong>Example to illustrate when a local and a global variable have same name<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint var = 15;     \/\/global variable\n\nint main() {\n  int var = 2;        \/\/local variable\n  cout&lt;&lt;var;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">2<\/div>\n<p>When a local and a global variable have the same name, we can access the global variable using scope resolution operator (::).<\/p>\n<p><strong>Example to show how to access a global variable when its name is same as that of a local variable<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint var = 15;     \/\/global variable\n\nint main() {\n  int var = 2;        \/\/local variable\n  cout&lt;&lt;\"Global variable = \"&lt;&lt;::var&lt;&lt;endl;\n  cout&lt;&lt;\"Local variable = \"&lt;&lt;var;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Global variable = 15<br \/>\nLocal variable = 2<\/div>\n<h3>Some other types of variables in C++<\/h3>\n<h4>1. Static Variables in C++<\/h4>\n<p>Static variables are defined using the static keyword. These retain their value even when they are no longer in use. They are only initialized once and exist till the program is terminated. They are local to the function in which they are defined.<\/p>\n<p>Default initial value of a static variable is 0.<\/p>\n<p><strong>Example of static variables in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nvoid sfun() {\n    int a = 10;\n    static int b = 10;\n    cout&lt;&lt;\"a = \"&lt;&lt;a++&lt;&lt;\"    \";\n    cout&lt;&lt;\"b = \"&lt;&lt;b++&lt;&lt;endl;\n}\n\nint main() {\n  for(int i=0; i&lt;3; i++) {\n      sfun();\n  }\n  return 0;\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">a = 10 b = 10<br \/>\na = 10 b = 11<br \/>\na = 10 b = 12<\/div>\n<p>Observe that unlike the variable a, static variable b does not reinitialize. It retains its value.<\/p>\n<h4>2. Automatic Variables in C++<\/h4>\n<p>Using the auto keyword, the data type of a variable is automatically deducted by the compiler from the value assigned to it.<\/p>\n<p>Scope of auto variables is local to the function in which they are defined. Their default initial value is garbage value.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<p>auto n = 10;<br \/>\nauto word = &#8220;TechVidvan&#8221;;<\/p>\n<h4>3. External Variables in C++<\/h4>\n<p>The extern keyword simply indicates that the variable is defined outside of the block in which it is being used. It is a global variable that is declared and initialized to be used somewhere else. The key purpose of extern variables is that they can be accessible from two separate files inside a larger program.<\/p>\n<p>Their default initial value is 0.<\/p>\n<p><strong>Example of extern variable in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint x;\n\nvoid efun() {\n    extern int x;       \/\/Indicating that x is defined elsewhere\n    x = 2;              \/\/Modifying the value of x\n    cout&lt;&lt;\"Modified value of extern variable x = \"&lt;&lt;x;\n}\n\nint main() {\n    cout&lt;&lt;\"x = \"&lt;&lt;x&lt;&lt;endl;\n  efun();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">x = 0<br \/>\nModified value of extern variable x = 2<\/div>\n<h3>Summary<\/h3>\n<p>This article covers all about variables in C++.<\/p>\n<p>We learnt the rules to name a variable, how to define and initialize it. Then, we learnt about the scope of variables in C++. On the basis of scope, variables are of two types namely, local variables and global variables. We understood how to handle local and global variables with examples.<\/p>\n<p>We also discussed the situation when a local variable and a global variable have the same name. Lastly, we learnt about static, automatic and external variables.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about variables in C++. In a program, the basic unit of storage is a variable. It is a name given to a location in memory that stores some&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":81714,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[3697,3698,3699,3700],"class_list":["post-81411","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-global-variable-in-c","tag-local-variable-in-c","tag-variable-scope-in-c","tag-variables-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Variables in C++ - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn what are variables in C++. On the basis of scope, variables are of two types - local and global variables. Learn these with examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Variables in C++ - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn what are variables in C++. On the basis of scope, variables are of two types - local and global variables. Learn these with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-08T03:30:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Variables-in-C.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Variables in C++ - TechVidvan","description":"Learn what are variables in C++. On the basis of scope, variables are of two types - local and global variables. Learn these with examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"Variables in C++ - TechVidvan","og_description":"Learn what are variables in C++. On the basis of scope, variables are of two types - local and global variables. Learn these with examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-08T03:30:41+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Variables-in-C.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Variables in C++","datePublished":"2021-07-08T03:30:41+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/"},"wordCount":949,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Variables-in-C.jpg","keywords":["Global Variable in C++","Local Variable in C++","Variable Scope in C++","Variables in C++"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/","url":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/","name":"Variables in C++ - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Variables-in-C.jpg","datePublished":"2021-07-08T03:30:41+00:00","description":"Learn what are variables in C++. On the basis of scope, variables are of two types - local and global variables. Learn these with examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Variables-in-C.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Variables-in-C.jpg","width":1200,"height":628,"caption":"Variables in C++"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Variables in C++"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81411","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81411"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81411\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/81714"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81411"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81411"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81411"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}