Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the line starting with double quote mean in C?

Tags:

c

I was asked in one of the interviews, what does the following line print in C? In my opinion following line has no meaning:

"a"[3<<1];

Does anyone know the answer?

like image 993
user1516141 Avatar asked Jul 10 '12 22:07

user1516141


3 Answers

Surprisingly, it does have a meaning: it's an indexing into an array of characters that represent a string literal. Incidentally, this particular one indexes at 6, which is outside the limits of the literal, and is therefore undefined behavior.

You can construct an expression that works following the same basic pattern:

char c = "quick brown fox"[3 << 1];

will have the same effect as

char c = 'b';
like image 103
Sergey Kalinichenko Avatar answered Sep 28 '22 09:09

Sergey Kalinichenko


Think of this:

"Hello world"[0] 

is 'H'

"Hello world" is a string literal. A string literal is an array of char and is converted to a pointer to the first element of the array in an expression. "Hello world"[0] means the first element of the array.

like image 37
ouah Avatar answered Sep 28 '22 08:09

ouah


It does have meaning. Hint: a[b] means exactly the same as *(a+b). (I don't think this is a great interview question, though.)

like image 34
Gareth McCaughan Avatar answered Sep 28 '22 08:09

Gareth McCaughan