For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
Now Reading
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
67. static_cast in C++
68. C++ Comments
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
73. Polymorphism in C++
74. Oops Concepts in C++
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
A variable is a fundamental building block in programming. We can think of it as a named container that resides in our computer's memory. This container can hold different types of data, just like a box can hold various items.
For example, let us assume that we have a set of labeled boxes. One might be labeled "Age," another "Name," and yet another "Favorite Color". Each box can store a specific type of information. A variable is similar, it has a name (like the box label) and holds a value of a specific type (like the contents of the box).
Let us learn more about the different types of variables in C++ and how we can use them effectively in C++ programming.
Here are some key points associated with using a C++ variable:
A C++ variable serves the same purpose in the world of C++ programming as variables in other scripting/programming languages. We use various different variables to store all kinds of information to be used in C++ programs.
Example:
int age = 25; // Variable to store a person's age
std::string name = "Alice"; // Variable to store a person's name
// Using the variables
std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;
In this C++ string variable example, age and name are variables. The program can then use these variables to display a personalized greeting.
C++ offers a wide range of variable types to store different kinds of data. Understanding these types is crucial for writing efficient and correct code. Let us look at the are the common C++ variable types.
These are fundamental data types provided by C++ to represent common forms of information:
C++ lets us create our own data types tailored to our specific needs:
Before we can use a C++ variable in our program, we need to introduce it to the compiler. This involves two steps:
Syntax:
dataType variableName = initialValue; |
In the above C++ variable syntax:
Example:
int age = 25; // Declares an integer variable named 'age' and initializes it with the value 25.
double price = 9.99; // Declares a double variable named 'price' and initializes it with the value 9.99.
char grade; // Declares a character variable named 'grade' (not initialized).
Example in a program structure:
#include <iostream>
#include <string>
int main() {
int age = 30; // Integer
double weight = 75.5; // Floating-point
char grade = 'A'; // Character
bool isStudent = true; // Boolean
std::string name = "Alice"; // Custom type: String
// ... your code here ...
return 0;
}
The data type we choose for a variable is crucial:
Choosing appropriate names for our variables is essential for code readability and maintainability. Here are some best practices:
In C++, we can declare a variable without initializing it. However, this can lead to undefined behavior because the variable might contain a garbage value from memory. It's generally good practice to initialize variables with a default value when we declare them.
Now that you are aware of how many types of variables in C++ exist, let us look at a C++ variable example program that you can run and try out yourself:
Code:
#include <iostream>
int main() {
// Variable Declaration and Initialization
double celsius = 25.0; // Temperature in Celsius
double fahrenheit; // Variable to store the converted temperature
const double CONVERSION_FACTOR = 9.0 / 5.0; // Constant for conversion formula
// Calculation
fahrenheit = (celsius * CONVERSION_FACTOR) + 32.0;
// Output
std::cout << "Temperature in Celsius: " << celsius << "°C" << std::endl;
std::cout << "Temperature in Fahrenheit: " << fahrenheit << "°F" << std::endl;
return 0;
}
In the above C++ variable example, we use double celsius = 25.0; to declare a variable named celsius of the double data type (floating-point number). We assign the initial value 25.0 to the celsius variable. Similarly, we use double fahrenheit; to declare another variable named fahrenheit of the double data type. We declare the variable but do not assign an initial value to it as it will be assigned later after the conversion.
If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.
While the basics of variables are essential, C++ offers some advanced features that give you more control over their behavior and usage. Let us explore some advanced C++ variable concepts.
Modifiers are keywords that we can apply to variable declarations to change their properties:
Example:
const double PI = 3.14159;
PI = 3.0; // Error! You can't change the value of a const variable.
Example:
void myFunction() {
static int counter = 0;
counter++; // This value persists between function calls
std::cout << "Function called " << counter << " times." << std::endl;
}
A reference is an alias (another name) for an existing variable. It's like a nickname for the C++ variable, and any changes made through the reference directly affect the original variable.
Example:
int originalValue = 10;
int& refValue = originalValue; // Declare a reference to originalValue
refValue = 20; // Modifies originalValue through the reference
std::cout << originalValue; // Output: 20
A pointer is a variable that stores the memory address of another variable. It is like having a signpost that points to the location where the data is stored.
Example:
int num = 5;
int* ptr = # // Declare a pointer named 'ptr' and assign it the address of 'num'
std::cout << *ptr; // Output: 5 (dereferencing the pointer to get the value)
Different C++ variable types are indispensable in programming for several reasons:
Fundamentally, variables are named containers in memory that store data of different types, enabling programs to manipulate and track information throughout their execution. They are fundamental for capturing user input, performing calculations, and making code adaptable to various scenarios.
Finally, according to me, choosing appropriate data types and meaningful names is absolutely crucial for writing clear and efficient code. If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.
If we had to define variable in C++, we could define it as a named memory location that stores a value of a specific data type. It acts as a container to hold and manipulate data during the execution of a program.
You declare a variable in C++ by specifying its data type followed by the variable name, optionally followed by an initial value (e.g., int age = 25;).
C++ has built-in data types like int, double, char, and bool, as well as custom data types like struct, class, and enum.
Yes, you can change the value of a variable in C++ unless it's declared as const.
Variable names in C++ must start with a letter or underscore, can include letters, numbers, and underscores, and should not be reserved keywords.
While it's not strictly required to initialize variables when declared, it's good practice to do so to prevent undefined behavior.
The scope of a variable in C++ can be local (limited to a block of code) or global (accessible throughout the program).
Yes, variables in C++ can have different data types depending on the kind of information they need to store.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.