Drax
Drax

Reputation: 161

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?

Upvotes: 2

Views: 103

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

In this subscripting expression

"20"[1]

"20" is a string literal that has the type char[3]. Used in expressions the literal is converted to pointer to its first element.

So this expression

"20"[1]

yields the second element of the string literal that is '0'.

You can imagine this record like

char *p = "20";

char c = p[1];

48 is the ASCII value of the character '0'.

A more exotic record can look like

1["20"]

that is equivalent to the previous record.

From the C Standard (6.5.2.1 Array subscripting)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Here is a demonstrative program

#include <stdio.h>

int main(void) 
{
    printf( "\"20\"[1] == '%c' and its ASCII value is %d\n", "20"[1], "20"[1] );
    printf( "1[\"20\"] == '%c' and its ASCII value is %d\n", 1["20"], 1["20"] );

    return 0;
}

Its output is

"20"[1] == '0' and its ASCII value is 48
1["20"] == '0' and its ASCII value is 48

Upvotes: 1

Well, depending on your point of view it's either '0', 48, or 0x30.

#include <stdio.h>

int main()
  {
  printf("'%c' %d 0x%X\n", "20"[1], "20"[1], "20"[1]);

  return 0;
  }

The above prints

'0' 48 0x30

Upvotes: 3

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

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.

Upvotes: 7

Related Questions