C++ int Keyword
The int
keyword in C++ is used to declare variables of type integer. It is a built-in data type that stores whole numbers, both positive and negative, without decimal points.
The size of an int
typically depends on the system architecture and compiler but is commonly 4 bytes (32 bits) on most modern systems, allowing it to store values from -2,147,483,648
to 2,147,483,647
.
Syntax
</>
Copy
int variable_name = value;
- int
- The keyword used to declare an integer variable.
- variable_name
- The name of the variable being declared.
- value
- An optional initial value for the variable, which must be a whole number.
Examples
Example 1: Declaring and Initializing an int
Variable
In this example, you will learn how to declare and initialize an int
variable and display its value.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int age = 25; // Declare and initialize an integer variable
cout << "Age: " << age << endl;
return 0;
}
Output:
Age: 25
Explanation:
- The variable
age
is declared as anint
and initialized with the value25
. - The
cout
statement prints the value ofage
to the console.
Example 2: Performing Arithmetic Operations with int
In this example, you will learn how to do arithmetic operations using int
variables.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
int sum = a + b;
int difference = a - b;
cout << "Sum: " << sum << endl;
cout << "Difference: " << difference << endl;
return 0;
}
Output:
Sum: 15
Difference: 5
Explanation:
- The variables
a
andb
are declared asint
and initialized with values10
and5
, respectively. - The arithmetic operations
a + b
anda - b
are performed, and the results are stored insum
anddifference
. - The results are printed using
cout
.
Example 3: Comparing int
Values
In this example, you will learn how to compare two int
variables using relational operators.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
if (x < y) {
cout << "x is smaller than y." << endl;
} else {
cout << "x is not smaller than y." << endl;
}
return 0;
}
Output:
x is smaller than y.
Explanation:
- The variables
x
andy
are declared asint
and initialized with values10
and20
, respectively. - The
if
statement comparesx
andy
using the<
operator. - Since
x
is smaller thany
, the first branch of theif
statement is executed.
Key Points about int
Keyword
- The
int
keyword declares variables that store whole numbers. - An
int
variable typically occupies 4 bytes (32 bits) on most systems. - It can store values ranging from
-2,147,483,648
to2,147,483,647
(for 32-bit systems). - Use
int
for variables when fractional values are not needed. - It supports arithmetic, relational, and logical operations.