Initialize all the elements of an array to the same number
There are many ways to fill an array with the same value, and if you are concerned about performance then you need to measure.
C++ has a dedicated function for filling an array with a value, and I would use this (after #include <algorithm>
and #include <iterator>
):
std::fill(std::begin(A), std::end(A), 3);
You shouldn't underestimate what optimizing compilers can do with something like this.
If you are interested in seeing what the compiler does, then Matt Godbolt's Compiler Explorer is a very good tool if you're prepared to learn a little bit of assembler. As you can see from here, compilers can optimize the fill
call to twelve (and a bit) 128-bit stores with any loops unrolled. Because compilers have knowledge of the target environment they can do this without encoding any target-specific assumptions in the source code.
He assumes that long
is four times longer than short
(that is not guaranteed; he should use int16_t and int64_t).
He takes that longer memory space (64 bits) and fills it with four short (16 bits) values. He is setting up the values by shifting bits by 16 spaces.
Then he wants to treat an array of shorts as an array of longs, so he can set up 100 16-bit values by doing only 25 loop iteration instead of 100.
That's the way your teacher thinks, but as others said this cast is undefined behavior.
What an absolute load of hogwash.
For starters,
v
will be computed at compile time.The behaviour of dereferencing
B
followinglong *B = (long*)A;
is undefined as the types are not related.B[i]
is a dereference ofB
.There's no justification whatsoever for the assumption that a
long
is four times larger than ashort
.
Use a for
loop in the simple way and trust the compiler to optimise. Pretty please, with sugar on top.