4 ms·
The behavior of [] is from C -- it's not a bizarro C++ feature. The "redefining keywords" is the pre-processor. That's what it does. There isn't anything mag
by olliej 14y ago
The behavior of [] is from C -- it's not a bizarro C++ feature.
The "redefining keywords" is the pre-processor. That's what it does. There isn't anything magic here. Strictly speaking it can be run entirely ahead of the C/C++ compiler, on any file you want. There's no requirement that it is C/C++ - you could use it on a python script (as long as you weren't using # comments anywhere :D )
- dljsjr 14y agoDefinitions of obscure: 1. Not easily distinguished 2. Not readily understandable/expressable 3. Not commonly known I didn't see the author use the word "bizarro" anywhere, nor make any claims about any of this stuff being weird. He actually presented almost everything in a fairly neutral tone, except when he said that using the preprocessor to override keywords was dangerous (which could be construed as opinion).
- bcoates 14y agoIt's not an opinion, it's forbidden by the language specification so it's not portable.
- pubby 14y agoThere is somewhat of a requirement with the preprocessor - if you redefine a keyword and then include a standard library header it's considered undefined behavior. Maybe that's what the author meant.
- nawitus 14y ago>The behavior of [] is from C -- it's not a bizarro C++ feature. I'd say that a feature of C++ is still a feature of C++ even if the same feature is in C.
- _pmf_ 14y agoThe point was probably that it is not obscure; it's what you had to learn when using plain C in the first week.
- Poyeyo 14y agoAnd the next week, and six months after that, again.
- eswangren 14y agoSeriously? It's not a difficult concept to understand...
- ycombobreaker 14y agoWhile it's definitely a rarely-used feature, the equivalence a[b] == *(a + b) == b[a] is fundamental to pointer math. Once you grok pointer math, then this is an interesting bit of syntax trivia and should not be forgotten easily.
- axusgrad 14y agocalling a[5] isn't obscure, but 5[a] sure is!
- papsosouid 14y agoExcept you didn't have to learn it as part of learning C, you didn't have to learn C to learn C++, and I would bet 99% of C and C++ programmers have no idea that 5[p] is valid code.
- qb45 14y agoMoreover, 3[a] appears to be supported solely for backwards compatibility with C since it works only for pointers - you can't do this with classes which define operator[](int).
- ori_b 14y agoThat's because operator overloading in C++ isn't commutative in general. For integers, 'a + b' is the same as 'b + a', but it's not the same in C++. For example, I could do: class MyClass {int operator+(int a) { return a; }}; MyClass x; x + 1; // Valid. 1 + x; // Type error. EDIT: My mistake. C++ requires these operators to be nonstatic member functions: = -> [] () Which, annoyingly enough, means that you can define '+' over types that you haven't implemented, but you can't define [] or =.