×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

unsigned int vs size_t in C

In this tutorial, we will learn about how to create unsigned int and size_t and differentiate between them?
Submitted by Shubh Pachori, on July 10, 2022

unsigned int

An unsigned int means the datatypes that can store only the positive values. i.e; from 0 onwards. The size of an unsigned int is 4 bytes and its range is 0 to 4294967295. The format specifier %u is used for unsigned int.

C program for using of unsigned int

#include <stdio.h>

int main()
{
    unsigned int i; // an unsigned int variable
    
    for (i = 1; i < 10; i++) {
        // %u format specifier is used for it
        printf("%u\n", i); 
    }
    
    return 0;
}

Output:

1
2
3
4
5
6
7
8
9

size_t

size_t is an unsigned integral datatype which are defined in various header files like <stdio.h>, <stdint.h>, <stddef.h> etc. It is a type that is used to represent the size of the objects in bytes and is therefore used as the return type variable by the sizeof operator. It will always be positive. It is big enough to contain the size of the largest object that the system can handle or hold. Its size depends on the compiler if the compiler is of 32 bits then its size is as equal as the size of an unsigned int that is 32 bits. But if it is a typical 64 bits compiler then it would be an unsigned long long int that is 64 bits.

C program for using of size_t

#include <stdio.h>
#include <stdint.h>

int main()
{
    const size_t N = 1; // a size_t type variable
    int arr[N]; //an array
    
    for (size_t n = 0; n < N; n++)
        arr[n] = n;
    
    // size of a size_t variable
    printf("SIZE_MAX = %zu\n", SIZE_MAX); 
    
    size_t size = sizeof arr;
    
    printf("size = %zu\n", size);
    
    return 0;
}

Output:

SIZE_MAX = 18446744073709551615
size = 4

Difference between unsigned int and size_t

So, if we consider the standard system of 32 bits both are integers of the same size that is 32 bits and ranges but if we use a typical 64 bits system, the size_t will be 64 bits but the unsigned int is of 32 bits. So, we cannot use them interchangeably. In 64 bits system, size_t is as big as an unsigned long long int.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.