Variables

Variables

Variables

Variables in C++ are used to store values that can be manipulated or used by the program. To declare a variable in C++, you need to specify the data type of the variable and give it a name. Here’s an example:

				
					int x; // declares a variable called x of type int 
				
			

This declares a variable called x of type int. The variable x can now be assigned a value, like this:

x = 42; // assigns the value 42 to the variable x

Alternatively, you can declare and initialize a variable in a single statement, like this:

int y = 10; // declares and initializes a variable called y of type int with the value 10

 

C++ has several built-in data types, including:

  • int: integers (whole numbers) with a range of -2147483648 to 2147483647
  • float: single-precision floating-point numbers with a range of approximately 1.2E-38 to 3.4E+38 and a precision of 6 decimal places
  • double: double-precision floating-point numbers with a range of approximately 2.2E-308 to 1.8E+308 and a precision of 15 decimal places
  • bool: boolean values (true or false)
  • char: single characters

Here are some examples of variable declarations and assignments for each of these data types:

				
					float f = 3.14159;
double d = 3.141592653589793; 
bool b = true; 
char c = 'a'; 

				
			

In addition to these built-in data types, C++ also allows you to define your own custom data types using structures and classes.

Join To Get Our Newsletter
Spread the love