C++ variables
Created By: chatGPT
In C++, variables are used to store data that your program can use. Each variable has a specific type that determines the size, layout, and the range of values it can hold. You can create variables for various types such as integers, floating-point numbers, characters, and more. Here are the most common data types:
- int: used for integer values
- float: used for single-precision floating-point values
- double: used for double-precision floating-point values
- char: used for storing a single character
To declare a variable, you need to specify the type followed by the variable's name. Here’s how you can do it:
int age;
float salary;
double temperature;
char grade;
You can also initialize a variable at the time of declaration. This means giving it a value right away. For instance:
int age = 25;
float salary = 45000.50;
double temperature = 98.6;
char grade = 'A';
C++ also supports string variables to store sequences of characters. To use strings, you need to include the <string>
library. Here’s how to declare and initialize a string variable:
#include <string>
std::string name = "John Doe";
You can change the value of a variable at any time, which is called re-assignment. For example:
age = 30;
salary = 50000.00;
name = "Jane Smith";
Finally, it's important to remember that variable names should be meaningful and follow certain naming conventions. They should start with a letter or underscore, contain only letters, digits, and underscores, and should not use any reserved keywords. Here’s an example of valid variable names:
int employeeCount;
float totalSales;
char favoriteLetter;