Search code examples
carraysarray-indexing

What does "20"[1] do?


In a test exam, we were told to find the value of some expressions.

All but 1 were clear, which was "20"[1]. I thought it was the 1st index of the number, so 0, but testing with a computer it prints 48.

What exactly does that 'function' do?


Solution

  • It's not a function, it's just indexing an array.

    "20" here is a character array, and we're taking the value at index 1 - which is '0' - the character '0'.

    This is the same as

    char chArr[] = "20";       // using a variable to hold the array 
    printf ("%d", chArr[1]);   // use indexing on the variable, decimal value 48
    printf ("%c", chArr[1]);   // same as above, will print character representation, 0
    

    The decimal value of '0' is 48, according to ASCII encoding, the most common encoding around these days.