Printing Array Elements

The expected output of the next C program is to print the elements of an array. But with the actual launch, it does not.

#include<stdio.h>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))

int array[] = {23,34,12,17,204,99,16};

int main()
{
    int d;

    for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
        printf("%d\n",array[d+1]);

    return 0;
}

What is the reason?

+3
source share
6 answers

When you perform a comparison d <= (TOTAL_ELEMENTS-2), type conversion is performed. dhas a type signed int, but (TOTAL_ELEMENTS-2)has a type size_tthat is an unsigned type. C rules say that when an operator has a signed and unsigned argument, and the unsigned argument is larger or equal to the signed argument, the signed argument is converted to unsigned.

That is, the comparison ends as:

(size_t) d <= (TOTAL_ELEMENTS-2)

size_t , (size_t) -1 - , , -1. 32- size_t 2 32 - 1 = 4 294 967 295.

, int:

d <= (int) (TOTAL_ELEMENTS-2)

, , ..

. gcc, , , -Wall -Wextra:

$ gcc -o arrayprint -Wall -Wextra -ansi arrayprint.c 
arrayprint.c: In function β€˜main’:
arrayprint.c:11: warning: comparison between signed and unsigned
+5

TOTAL_ELEMENTS . -1, unsigned, , 6. , .

+6
. GCC, :
$ gcc -Wall -Wextra -Os a.c
a.c: In function `main':
a.c:11: warning: comparison between signed and unsigned

, :

(int) -1 <= (size_t) 5

, - , . size_t. :

(size_t) -1 <= (size_t) 5

-1 . , 2 ^ 32 ( size_t), 4294967295. , :

4294967295 <= 5

false, .

+3

, . , TOTAL_ELEMENTS size_t, .

, (TOTAL_ELEMENTS-2) int.

+1

:

for(d=0;d < TOTAL_ELEMENTS;d++)
    printf("%d\n",array[d]);

as sizeof(...) .

0

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))

#define TOTAL_ELEMENTS (int)(sizeof(array)/sizeof(array[0]))-2
0

Source: https://habr.com/ru/post/1757569/


All Articles