c++character-literals

How to compile the extended character in C++ using GCC?


The following code fails to compile using GCC:

int main()
{
    for(int j=0; j<80; j++) //for every column,
    { //ch is ‘x’ if column is
        char ch = (j%8) ? ‘ ‘ : ‘x’; //multiple of 8, and
        cout << ch; //‘ ‘ (space) otherwise
    }
    return 0;
}

It should print: x x x x x x x x x

But I get the following error:

error: extended character ‘ is not valid in an identifier


Solution

  • In this line:

    char ch = (j%8) ? ‘ ‘ : ‘x’;
    

    You are using the wrong single-quote.
    The proper one is ', i.e.:

    //----------------V-V---V-V-
    char ch = (j%8) ? ' ' : 'x';
    

    This is specified in the Character literal documentation.