• the index of one array that can not overflow

    From Rosario19@Ros@invalid.invalid to comp.lang.c on Thu Oct 23 20:39:12 2025
    From Newsgroup: comp.lang.c



    here the unsigned chars are 8 bit unsigned...
    here the index i it seems always definited from 0 to 255
    and so it is always definited a[i], but one can make errors the same
    in other places...


    #include <stdio.h>

    main(void)
    {unsigned char a[258]="0123456789", i;
    unsigned c;
    for(c=i=0;c<500;++c,++i)
    printf("%c",a[i]);
    printf("\n");
    return 0;
    }

    result

    index
    0123456789
    0123456789

    --- Synchronet 3.21a-Linux NewsLink 1.2
  • From minforth@minforth@gmx.net to comp.lang.c on Thu Oct 23 21:24:31 2025
    From Newsgroup: comp.lang.c

    Am 23.10.2025 um 20:39 schrieb Rosario19:


    here the unsigned chars are 8 bit unsigned...
    here the index i it seems always definited from 0 to 255
    and so it is always definited a[i], but one can make errors the same
    in other places...


    #include <stdio.h>

    main(void)
    {unsigned char a[258]="0123456789", i;
    unsigned c;
    for(c=i=0;c<500;++c,++i)
    printf("%c",a[i]);
    printf("\n");
    return 0;
    }

    result

    index
    0123456789
    0123456789


    Ada does it better ...
    --- Synchronet 3.21a-Linux NewsLink 1.2
  • From Keith Thompson@Keith.S.Thompson+u@gmail.com to comp.lang.c on Thu Oct 23 15:30:48 2025
    From Newsgroup: comp.lang.c

    Rosario19 <Ros@invalid.invalid> writes:
    here the unsigned chars are 8 bit unsigned...
    here the index i it seems always definited from 0 to 255
    and so it is always definited a[i], but one can make errors the same
    in other places...


    #include <stdio.h>

    main(void)
    {unsigned char a[258]="0123456789", i;
    unsigned c;
    for(c=i=0;c<500;++c,++i)
    printf("%c",a[i]);
    printf("\n");
    return 0;
    }

    result

    index
    0123456789
    0123456789

    Obviously "main(void)" should be "int main(void)".

    Yes, if you use an unsigned char value as an array index, and the
    array has at least UCHAR_MAX+1 (typically 256) elements, then the
    indexing operation can't go outside the bounds of the array.

    It's difficult to imagine this actually being useful. There
    might be some cases where you want an index to wrap around from
    255 to 0, but this method doesn't allow for different lengths.
    If you want an index to wrap around from 99 to 0, you have to do
    it explicitly. You might as well do it explicitly in this case
    as well. The resulting code would be a lot more legible and robust.

    Also, you seem not to have noticed that you're printing the '\0'
    characters that occupy most of your array.
    --
    Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
    void Void(void) { Void(); } /* The recursive call of the void */
    --- Synchronet 3.21a-Linux NewsLink 1.2