5 ms·
My favorite proof that C arrays and strings are actually just syntactic sugar for pointer arithmetic is that the following are all valid and equivalent: ch
by DonHopkins 8y ago
My favorite proof that C arrays and strings are actually just syntactic sugar for pointer arithmetic is that the following are all valid and equivalent:
char theLetterC = "ABC"[2];
char theLetterC = *("ABC" + 2);
char theLetterC = *(2 + "ABC");
char theLetterC = 2["ABC"];
"You can't prove anything about a program written in C or FORTRAN. It's really just Peek and Poke with some syntactic sugar." -Bill Joy
- huhtenberg 8y ago> Peek and Poke Now that's the words I haven't heard in a long time.
- danlugo92 8y agochar theLetterC = 2["ABC"]; Wait, what? And I thought I was good with pointers... Edit: I think I got it, is it this?: "ABC" + 2 == 2["ABC"] == *(2 + "ABC") Right?
- deleted 8y ago[deleted]
- aasasd 8y agoI'm not a C man, but afaiu, "ABC" is syntactic sugar for a char pointer to that string. So it works like any pointer with regard to index access.
- p1esk 8y agochar theLetterC = 2["ABC"]; ???
- DonHopkins 8y agoIn object oriented terms, the number two is an infinite map from all possible strings, to the third character of each string (or undefined behavior if the string length is too short). That just happens to be highly optimized in C. ;) In Objective C, that would be [2 getNthCharacterOfCString: "ABC"]; Just joking! If you try to think about C in object oriented terms, you're misunderstanding what's really going on. It doesn't actually have arrays or strings as objects, they're just syntactic sugar (more like syntactic syrup of ipecac), and [] doesn't send a message. It's all just pointer arithmetic.
- vram22 8y agoYes, that works because for an array arr and an int i, arr[i] (i'th element of array arr) is the same as *(arr + i) (the value at the memory address arr + i) which is the same (by commutativity) as *(i + arr) (the value at the memory address i + arr) which in turn is the same as i[arr] That last bit is what seems non-intuitive, but it is true. I first read about this, maybe in the K&R book or some other C book, many years ago, at first didn't believe it, and remember trying it out on at least a Windows C compiler (MS C, likely) and maybe GCC on Linux as well. Worked on both, no compiler error. This works because the expression arr, while we think of it as the name of the declared array, is also a synonym for the address of the first memory location of the array. Note: all that I wrote above is what I rememeber from using ANSI C (a lot, but some years earlier). Things may have changed some with C99, etc.
- vram22 8y ago>rememeber remember