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:

  1. The variable age is declared as an int and initialized with the value 25.
  2. The cout statement prints the value of age 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:

  1. The variables a and b are declared as int and initialized with values 10 and 5, respectively.
  2. The arithmetic operations a + b and a - b are performed, and the results are stored in sum and difference.
  3. 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:

  1. The variables x and y are declared as int and initialized with values 10 and 20, respectively.
  2. The if statement compares x and y using the < operator.
  3. Since x is smaller than y, the first branch of the if statement is executed.

Key Points about int Keyword

  1. The int keyword declares variables that store whole numbers.
  2. An int variable typically occupies 4 bytes (32 bits) on most systems.
  3. It can store values ranging from -2,147,483,648 to 2,147,483,647 (for 32-bit systems).
  4. Use int for variables when fractional values are not needed.
  5. It supports arithmetic, relational, and logical operations.