MOCKSTACKS
EN
Questions And Answers

More Tutorials








C++ Declare Variables

To declare a variable in C++ you will need to specify the data type foe that variable, give it a name and set a value. C++ does support multiple variables declaration in 1 single line.

Variables in C++ can be declared in 2 categories:
  • Global variables
  • Local Variables

C++ Declare variable syntax

data_type variable1_name = value1;
data_type variable2_name = value2, variable3_name = value3;

Example of C++ variable declaration

#include<iostream>

using namespace std;

int main()
{
  int num1=100, num2=200;
  int num3 = 300;
  return 0;
}


Example Of C++ Global variable

C++ Global variables will be defined outside functions including main() and it will accessible to all functions within same class.

#include <iostream>
using namespace std;

char myVar = 'A';

int main()
{
   cout <<"Value of myVar: "<< myVar<<endl;
   myVar='Z';
   cout <<"Value of myVar: "<< myVar;
   return 0;
}

Output

Value of myVar: A
Value of myVar: Z


Example Of C++ Local variable

C++ Local variables will be defined within functions and it will accessible to only the function that is defining it.

#include <iostream>
using namespace std;

int main()
{
   char myVar = 'A';
   cout <<"Value of myVar: "<< myVar<<endl;
   myVar='Z';
   cout <<"Value of myVar: "<< myVar;
   return 0;
}

Output

Value of myVar: A
Value of myVar: Z

Conclusion

In this page (written and validated by ) you learned about C++ Declare Variables . What's Next? If you are interested in completing Cpp tutorial, your next topic will be learning about: Cpp Data Types.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.