On 08/03/2019 09:55, fir wrote:
>
> besides does you maybe know, or somebody
> thet when you got (in C, primary sasking on C here)
>
> struct Some {int x,t,z; };
>
> for(;;)
> {
> Some x = { 10, 20, 30 };
>
> }
>
> is this line inside a loop considered always as an initialization or
> is it considered maybe as assigment / some combination of
> initialization and assigment
It is a definition and initialisation. As far as C is concerned, the
lifetime of "x" starts when the loop's block is entered, and ends when
the loop's block ends. Logically, "x" is created anew at the start of
the block (once per loop), then initialised anew with these values. At
the end of the loop, it is destroyed.
In C, "constructing" an automatic variable is usually no more than a
stack pointer change, or using a register. Initialisation is just
setting the data in the stack frame or the register. "Destruction" is
restoring the stack pointer. Initialisation and assignment of local
variables is generally identical - you don't see a difference between
"int x; x = 1;" and "int x = 1;" (except for const variables, and other
syntactic details).
In C++, objects can have more complicated constructors, destructors,
initialisation and assignment - but the principle is /exactly/ the same.
And in both cases, the compiler is free to optimise the code. Almost
invariably (when there are no VLA's or other big stack allocations),
compilers will do all necessary stack pointer manipulation in the
function prologue and epilogue, and not bother moving it up and down
within loops like this. This is identical for C and C++.
>
> can you remind me if
> for(;;)
> {
> x = { 10, 20, 30 };
>
> }
>
> works in c? im far from the compiler and cant check, and i dont remember
>
It works for initialisation, but not for assignment.
struct Some { int x, t, z; };
struct Some foo(void) {
struct Some x = {1, 2, 3}; // OK in C and C++
return x;
}
struct Some foo2(void) {
struct Some x;
x = (struct Some) {1, 2, 3}; // OK in C, not in C++
return x;
}
struct Some foo3(void) {
struct Some x;
x = {1, 2, 3}; // OK in C++11, not in C
return x;
}
(Compound literals as used in foo2 are in C99 and C11, but not in C++
except as compiler extensions - gcc allows them in C++, but I don't know
about other compilers.)