Variables:
A variable is a named storage location in a computer’s memory that holds a value. In C++, you need to declare a variable before using it. The basic syntax for variable declaration is:
data_type variable_name;
Here, data_type
is the type of data the variable will hold, and variable_name
is the name you give to the variable. For example:
int age; // Declaring an integer variable named 'age'
float salary; // Declaring a floating-point variable named 'salary'
char grade; // Declaring a character variable named 'grade'
Data Types:
C++ provides several built-in data types to represent different kinds of values. Here are some common data types:
Integer Types:
-
int
: Integer type (e.g.,int age = 25;
).short
: Short integer type.long
: Long integer type.long long
: Long long integer type.
int score = 100;
Floating-Point Types:
float
: Single-precision floating point.double
: Double-precision floating point (more precision thanfloat
).long double
: Extended precision floating point.
double temperature = 98.6;
Character Types:
char
: Character type (e.g.,char grade = 'A';
).
char initial = 'M';
Boolean Type:
bool
: Boolean type representingtrue
orfalse
.
bool isStudent = true;
Void Type:
void
: Represents the absence of type.
void printMessage() {
// Function with void return type
cout << "Hello, World!" << endl;
}
Modifiers:
Modifiers can be used with these basic data types to modify the amount of memory space allocated or to represent the range of values a variable can hold.
signed
andunsigned
can be used with integer types to represent both positive and negative or only positive values, respectively.short
,long
, andlong long
can be used to modify the size of integer types.
unsigned int positiveNumber = 100;
Constants:
Constants are variables whose values cannot be changed once they are assigned. Use the const
keyword to declare constants.
const double PI = 3.14159;