What is half open range and off the end value

后端 未结 3 767
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 16:01

What do these terminologies mean in C++?

1. off the end value

2. half open range - [begin, off_the_end)

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 16:38

    As explained on other answers, half-open range is also a mathematical term and usage of this term in programming context, it is implied that the starting point is included and end point is excluded.

    What does it actually mean in the context of programming in C/C++ ? Let's say, you are going to print the elements of an integer array. Speaking for the C language, because that you have no any run-time knowledge for the size of the array, you have two choice. Either you have to provide the size of the array and thus, the function signature will be as below;

    void printArray(int * array, int size);
    

    or you have to use the half-open range, which means, you have to provide both begin and end pointer (and function is going to process including the begin, excluding the end) additional to the array itself. And the function signature will be as below;

    void printArray(int * array, int * begin, int * end);
    

    To illustrate, here is an example for providing the size of the array;

    #include 
    
    void printArray(int * array, int size)
    {
        printf("Array: ");
    
        for(int i = 0; i < size; i++)
            printf("%2d ", array[i]);
    
        printf("\n");
    }
    
    int main()
    {
        int array[5] = { 1, 2, 3, 4, 5 };
    
        printArray(array, 5);
    
        return 0;
    }
    

    In the example above, we have passed two parameters to the printArray function as it is obvious on the function signature, the pointer to the first element of the array (or the array itself), and the size of the array.

    However, as I have written above, we can also use the half-opening range in the function signature which can be seen as below;

    #include 
    
    void printArray(int * array, int * begin, int * end)
    {
        printf("Array: ");
    
        for(int * index = begin; index != end; index++)
            printf("%2d ", *index);
    
        printf("\n");
    }
    
    int main()
    {
        int array[5] = { 1, 2, 3, 4, 5 };
    
        printArray(array, array, array+5);
    
        return 0;
    }
    

    Both of the code will produce the same output as can be seen below;

    Array:  1  2  3  4  5
    

    As you can see, the printArray function prints the function for the range [begin, end). The index which is actually is a pointer to the elements of the integer array, starts from begin, and it includes the begin and the for-loop ends up when index equals to the end pointer, excluding to process the end. This i called half-open range.

    Half-open range is the C++ convention.

提交回复
热议问题