user1516141
user1516141

Reputation: 61

What does the line starting with double quote mean in 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?

Upvotes: 5

Views: 280

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

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';

Upvotes: 13

sepp2k
sepp2k

Reputation: 370172

"some_string"[i] returns the ith character of the given string. 3<<1 is 6. So "a"[3<<1] tries to return the 6th character of the string "a".

In other words the code invokes undefined behavior (and thus, in a sense, really does have no meaning) because it's accessing a char array out of bounds.

Upvotes: 1

Alok Singhal
Alok Singhal

Reputation: 96141

"a" is an array of 2 characters, 'a', and 0. 3 << 1 is 3*2 = 6, so it's trying to access the 7th element of a 2-element array. That is undefined behavior.

(Also, the code doesn't print anything, even if the undefined behavior is removed, since no printing functions are called.)

Upvotes: 2

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

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.)

Upvotes: 3

ouah
ouah

Reputation: 145839

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.

Upvotes: 3

Related Questions