Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 390
Drax Avatar asked Mar 19 '26 07:03

Drax


2 Answers

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.

like image 98
Sourav Ghosh Avatar answered Mar 21 '26 21:03

Sourav Ghosh


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
like image 35