Odd syntax in C++: return { .name=value, ... } -
while reading article, came across following function:
solidcolor::solidcolor(unsigned width, pixel color) : _width(width), _color(color) {} __attribute__((section(".ramcode"))) rasterizer::rasterinfo solidcolor::rasterize(unsigned, pixel *target) { *target = _color; return { .offset = 0, .length = 1, .stretch_cycles = (_width - 1) * 4, .repeat_lines = 1000, }; }
what author doing return statement? haven't seen before, , not know how search it... valid plain c too?
edit: link original article
this isn't valid c++.
it's (sort of) using couple features c known "compound literals" , "designated initializers", few c++ compilers support extension. "sort of" comes fact legitimate c compound literal, should have syntax looks cast, you'd have like:
return (rasterinfo) { .offset = 0, .length = 1, .stretch_cycles = (_width - 1) * 4, .repeat_lines = 1000, };
regardless of difference in syntax, however, it's creating temporary struct members initialized specified in block, equivalent to:
// possible definition of rasterinfo // (but real 1 might have more members or different order). struct rasterinfo { int offset; int length; int stretch_cycles; int repeat_lines; }; rasterinfo rasterize(unsigned, pixel *target) { *target = color; rasterinfo r { 0, 1, (_width-1)*4, 1000}; return r; }
the big difference (as can see) designated initializers allow use member names specify initializer goes member, rather depending solely on order/position.
Comments
Post a Comment