This earlier question asks what this[0]
means in C#. In C++, this[0]
means "the zeroth element of the array pointed at by this
."
Is it guaranteed to not cause undefined behavior in C++ to refer to the receiver object this way? I'm not advocating for using this syntax, and am mostly curious whether the spec guarantees this will always work.
Thanks!
C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
You cannot use 0 instead of null in your programs even though null is represented by the value 0. You can use null with any reference type including arrays, strings, and custom types.
if 0" means "exclude. always". This construct is used to comment out a block of code that is not being.
gets(buf); The gets() function in C is inherently unsafe. The code below calls the gets() function to read in data from the command line. char buf[24];
For any valid object pointer p
, p[0]
is equivalent to *p
. So this[0]
is equivalent to *this
. There's nothing more to it. Just like you can dereference any valid pointer using [0]
, you can dereference this
with it.
In other words, it is just a "tricky" way to write *this
. It can be used to obfuscate code. It can probably be used in some specific circumstances for useful purposes as well, since any standalone object can be thought of as an array of size 1. (From C++03, Additive operators: "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.")
P.S. As Johannes noted in the comments, by using C++11 features it is possible to come up with a context in which this
is a pointer to an incomplete type. In that case this[0]
expression becomes invalid, while *this
expression remains valid.
this[0]
is the same as *(this + 0)
, so indeed this is fine (albeit a bit weird).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With