C++ vs D: Default param values and struct to array casting

Johan Engelen j at j.nl
Fri Sep 6 09:49:33 UTC 2019


On Friday, 6 September 2019 at 09:14:31 UTC, Andrew Edwards wrote:
> C++ allows the for following:
>
> struct Demo
> {
> 	float a, b, c, d;
> 	Demo() { a = b = c = d = 0.0f; }
> 	Demo(float _a, float _b, float _c, float _d) {
> 		a = _a;
> 		b = _b;
> 		c = _c;
> 		d = _d;
> 	}
> 	float  operator[] (size_t i) const { return (&a)[i]; } //[3]

"(&a)[i]" is undefined behavior in C++. You cannot index into 
struct members like that. Of course it may work in certain cases, 
but UB is UB. Don't do it!

I found a more detailed explanation for you: 
https://stackoverflow.com/questions/40590216/is-it-legal-to-index-into-a-struct

-Johan



More information about the Digitalmars-d-learn mailing list