Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "12345" + 2 do in C?

Tags:

c

I've seen this done in C before:

#define MY_STRING "12345"
...
#define SOMETHING (MY_STRING + 2)

What does SOMETHING get expanded to, here? Is this even legal? Or do they mean this?:

#define SOMETHING (MY_STRING[2])
like image 810
Joe Avatar asked Aug 25 '10 22:08

Joe


2 Answers

String literals exist in the fixed data segment of the program, so they appear to the compiler as a type of pointer.

+-+-+-+-+-+--+
|1|2|3|4|5|\0|
+-+-+-+-+-+--+
 ^ MY_STRING
     ^ MY_STRING + 2
like image 95
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 23:09

Ignacio Vazquez-Abrams


When you have an array or pointer, p+x is equivalent to &p[x]. So MY_STRING + 2 is equivalent to &MY_STRING[2]: it yields the address of the third character in the string.

Notice what happens when you add 0. MY_STRING + 0 is the same as &MY_STRING[0], both of which are the same as writing simply MY_STRING since a string reference is nothing more than a pointer to the first character in the string. Happily, then, the identity operation "add 0" is a no-op. Consider this a sort of mental unit test we can use to check that our idea about what + means is correct.

like image 41
John Kugelman Avatar answered Sep 30 '22 23:09

John Kugelman