LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   gcc Warning: Array index has type 'char' (https://www.linuxquestions.org/questions/programming-9/gcc-warning-array-index-has-type-char-636604/)

traene 04-20-2008 10:56 AM

gcc Warning: Array index has type 'char'
 
While trying to compile a programme, i get the following warning:

tokenizer.cpp:121: warning: array subscript has type 'char'

The array is a table mapping special meanings to the ASCII character sets. For instance i want to extract quotes, whitespace and such:

Code:

#include <stdio.h>
#include <string.h>

const char tokTable[128];

void parseInput(const char* input) {
    int posCount=0;
    while (*input) {
        if (tokTable[*input]==1){
            printf("found a space at pos: %d\n",posCount);
        }
        ++input; ++posCount;
    }
}

int main(int argc, const char** argv) {
    char* ptok=(char*)tokTable;
    bzero(ptok,sizeof(tokTable));
    ptok[32]=1; // space
    //tokTable[]; and so forth
    parseInput("Hey you!");
    return 0;
}

How can i fix the warning at: 'tokTable[*input]'

I am using gcc 4.3.0

Dan04 04-20-2008 01:05 PM

Cast it to int. But I can't see why it's giving a warning for a lossless conversion.

traene 04-20-2008 01:33 PM

That did the trick.

Thank you.

osor 04-20-2008 02:09 PM

Quote:

Originally Posted by Dan04 (Post 3127119)
But I can't see why it's giving a warning for a lossless conversion.

The warning is enabled by “-Wchar-subscripts” or its superset “-Wall” as a command-line option. It is only a warning (not an error), and your usage is valid C++. The reason there is a warning for this is that the type char may be signed, in which case a high-bit value might be a negative index in your subscript (which may or may not be what you want, but is a common source of bugs).

Dan04 04-20-2008 08:43 PM

That makes sense. I've been bitten by signed chars a few times.


All times are GMT -5. The time now is 11:40 AM.