c++ - C: Initializing struct variables after declaration -
i encountered not figure out why language allow b = c; below , fail b = {3, 4}. there issue allowing latter ?
struct t { int x; int y; }; int main() { t = {1, 2}; t b; b = {3, 4}; // why fail ? t c = {3, 4}; b = c; // works return 0; }
it fails because {3, 4}
, though it's valid initializer, not expression (at least isn't in c; see below more c++).
every expression in c has type can determined examining expression itself. {3, 4}
potentially of type struct t
, or int[2]
(an array type), or of myriad of other types.
c99 added new feature called compound literals use similar syntax initializers, let specify type, creating expression:
b = (struct t){3, 4};
note (struct t)
not cast operator; it's part of syntax of compound literal.
for more information on compound literals, see section 6.5.2.5 of draft c11 standard.
compound literals introduced 1999 iso c standard (c99). if compiler doesn't support c99 or better (*cough*microsoft*cough*), won't able use them.
if you're using c++ (which, don't forget, different language), doesn't support compound literals, there may alternative. potatoswatter points out in comment, this:
b = t{3, 4};
is valid in c++11 (but not in earlier versions of c++ language). covered in section 5.2.3 [expr.type.conf] of c++ standard.
for matter, this:
b = {3, 4};
is valid c++11 syntax. form can used in number of specified contexts, including right side of assignment. covered in section 8.5.4 [dcl.init.list] of c++ standard.
one recent draft of c++ standard n3485.
(g++ supports c99-style compound literals in c++ extension.)
and if you're stuck pre-c99 compiler, can write own initialization function, such as:
struct t init_t(int x, int y) { struct t result; result.x = x; result.y = y; return result; } /* ... */ struct t obj; /* ... */ obj = init_t(3, 4);
it's annoying amount of work (which why c99 added compound literals), job. on other hand, in cases you're better off using initialization:
struct t obj; /* ... */ { struct t tmp = { 3, 4 }; obj = tmp; }
which better depends on how program structured.
Comments
Post a Comment