Skip to content

Instantly share code, notes, and snippets.

@codewithmanas
Created February 25, 2023 14:20
Show Gist options
  • Save codewithmanas/3b15a36c1d5f3bb52a83e37891381f4b to your computer and use it in GitHub Desktop.
Save codewithmanas/3b15a36c1d5f3bb52a83e37891381f4b to your computer and use it in GitHub Desktop.
Do you know return type of sizeof() operator in C/C++ ?

return type of sizeof() operator is size_t

what is difference between size_t vs int data types?

size_t and int are two different data types in C that are used for different purposes.

int is a signed integer type that can represent both positive and negative values. It is commonly used for counting and arithmetic operations in C programs. However, the size of an int can vary depending on the implementation and architecture of the system, and it is not guaranteed to be the same size on all systems.

size_t is an unsigned integer type that is used to represent the size of an object or the result of the sizeof operator. It is guaranteed to be large enough to represent the size of any object on the system, and it is defined to be the same size as unsigned long on most systems. size_t is commonly used for memory allocation and manipulation operations, where the size of objects is important.

The main difference between size_t and int is that size_t is an unsigned type, meaning it can only represent non-negative values. This makes it well-suited for representing sizes, lengths, and indices, which cannot be negative values. Additionally, size_t is guaranteed to be large enough to represent the size of any object, regardless of the size of an int on the system.

In summary, int is used for general arithmetic operations and can represent both positive and negative values, while size_t is used for representing the size of objects and can only represent non-negative values.

Let's see the code for example

printf("size of integer is %d bytes\n", sizeof(int));

The code itself is not technically wrong, but it could lead to unexpected behavior if compiled on a system where the size of an int is not 4 bytes.

The %d format specifier is used to print an integer value with printf, but the sizeof operator returns a value of type size_t, which may not be the same size as an int on all systems. Therefore, using %d to print the result of sizeof(int) may result in incorrect output if the size of an int is not 4 bytes.

To fix this issue, you should use the correct format specifier for the sizeof operator, which is %zu. The zu specifier is used to print a size_t value, which is the type returned by the sizeof operator. The corrected code would be:

printf("size of integer is %zu bytes\n", sizeof(int));

This ensures that the correct format specifier is used for the sizeof operator, regardless of the size of size_t and int on the system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment