Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this[0] safe in C++?

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!

like image 957
templatetypedef Avatar asked May 20 '13 17:05

templatetypedef


People also ask

Is 0 a false value in C?

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.

Can we use 0 instead of null in C?

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.

What does if 0 mean in C?

if 0" means "exclude. always". This construct is used to comment out a block of code that is not being.

Is gets safe in C?

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


2 Answers

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.

like image 169
AnT Avatar answered Sep 17 '22 14:09

AnT


this[0] is the same as *(this + 0), so indeed this is fine (albeit a bit weird).

like image 45
Kerrek SB Avatar answered Sep 19 '22 14:09

Kerrek SB