Difference Between int and size_t in C++
Following are some key differences between int and size_t in C++:
Feature | int | size_t |
---|---|---|
Definition | Signed integer data type | Unsigned integer data type |
Header file | Defined in <stdio.h> | Defined in various header files such as: <stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h> |
Size | Normally 32 bits (but can vary) | Platform-dependent, same as the architecture’s pointer size |
Range | Ranges between -2,147,483,648 to 2,147,483,647 (for 32-bit) | Ranges between 0 to 4,294,967,295 or 0 to 18,446,744,073,709,551,615 (as per system) |
Negative Values | Can represent negative values | Cannot represent negative values. |
Purpose | General integer arithmetic | Representing sizes of objects in memory |
Compatibility | Compatible with both positive and negative arithmetic operations | Compatible with only non-negative values. |
Usage | Used to store,temperatures, coordinates, loop counters | Used to store sizes of arrays, strings, memory allocations |
C++ Program for Using Int
The following program demonstrates the use of int data type to perform arithmetic operations between negative and positive integers in C++:
// C++ Program Using Int to perform addition of a negative and a positive integer
#include <iostream>
using namespace std;
int main()
{
// use int for negative numbers
int num = -50;
int positive = 100;
// use int for arithmetic operations
int result = num + positive;
cout << "Result of adding " << num << " and " << positive << " is " << result << endl;
return 0;
}
Output
Result of adding -50 and 100 is 50
Time Complexity: O(1)
Auxiliary Space: O(1)
C++ Program for using Size_t
The following program demonstrates the use of size_t data type to store the size of an array in C++:
// C++ Program using Size_t to store the size of an array
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
// use size_t to store the number of elements in the array
size_t size = sizeof(arr) / sizeof(arr[0]);
// Iterate through the array using size_t and print the array elements
cout<<"Array Elements: ";
for (size_t i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout<<"\nSize of the array is: "<<size;
return 0;
}
Output
Array Elements: 1 2 3 4 5 Size of the array is: 5
Time Complexity: O(N), where N is the size of the array.
Auxiliary Space: O(1)
Difference Between int and size_t in C++
In C++, both int and size_t are very important data types that are used to represent integers. However, there are some key differences between them that the users should be aware of. In this article, we will learn the differences between int and size_t in C++.
Contact Us