undefined behavior

Discussion in 'C Programming' started by deepak, Jan 12, 2007.

  1. deepak

    deepak Guest

    Using 'char' as an array index is an undefined behavior?
    deepak, Jan 12, 2007
    1. Advertisements

  2. deepak

    Zara Guest

    No. the char will be promoted to int.
    Zara, Jan 12, 2007
    1. Advertisements

  3. No, though it might not be the best idea, as that limits you to being
    able to (portably) index only 128 elements of the array.
    Clark S. Cox III, Jan 12, 2007
  4. No, but if 'char' is 8-bit and signed, and contains an 8-bit character,
    then it is negative. So

    static char foo[256];
    void bar(char ch) { ... foo[ch] ... }
    can use a negative index to foo[], which yields undefined behavior.
    Use foo[(unsigned char)ch] instead.
    Hallvard B Furuseth, Jan 12, 2007
  5. [/QUOTE]
    Which is why some compilers (e.g. gcc) warn you about it.

    -- Richard
    Richard Tobin, Jan 12, 2007
  6. deepak said:
    No, but indexing outside the bounds of an array does invoke undefined
    behaviour. If the value stored in the char is negative (which it can be if
    char is signed by default) or greater than or equal to the number of
    elements in the array, the behaviour is undefined.
    Richard Heathfield, Jan 12, 2007
  7. int array[10] = { 0,1,2,3,4,5,6,7,8,9};

    int *p = &array[4];

    signed char index = -1; // signed for clarity

    printf("%d\n", p[index]);

    are you guys saying that any negative index is undefined behaviour or just
    that if you dereference before &array[0]?
    Serve Laurijssen, Jan 12, 2007
  8. Indexing an *array* with a negative index is undefined behavior, because
    negative indices are, by definition, out of bounds. As you have
    demonstrated, indexing a *pointer* with a negative index might not be;
    because that pointer might actually point into a larger array.
    Clark S. Cox III, Jan 12, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.