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
ageis declared as anintand initialized with the value25. - The
coutstatement prints the value ofageto 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
aandbare declared asintand initialized with values10and5, respectively. - The arithmetic operations
a + banda - bare performed, and the results are stored insumanddifference. - 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
xandyare declared asintand initialized with values10and20, respectively. - The
ifstatement comparesxandyusing the<operator. - Since
xis smaller thany, the first branch of theifstatement is executed.
Key Points about int Keyword
- The
intkeyword declares variables that store whole numbers. - An
intvariable typically occupies 4 bytes (32 bits) on most systems. - It can store values ranging from
-2,147,483,648to2,147,483,647(for 32-bit systems). - Use
intfor variables when fractional values are not needed. - It supports arithmetic, relational, and logical operations.
