Even when copying code, it is a good idea to stop and think for a second.
In particular, when we see a loop, think of the boundary conditions:
in this case, what would happen if
n is initially zero (the user entered zero)?
Also, don't copy obfuscated code blindly: transparent code is good code.
for instance,
val >> 1 does not optimize anything; people who write compilers would know at least as much about low level efficiency as the palooka who thinks that the code is being made more efficient by applying strength reduction at source code level.
For instance, in he best case scenario,
foo and
palooka_foo would generate the same machine code, as would
bar,
alt_bar,
palooka_bar and
palooka2_bar
1 2 3 4 5 6 7 8 9 10 11
|
unsigned int foo( unsigned int n ) { return n/2 ; }
unsigned int palooka_foo( unsigned int n ) { return n >> 1 ; }
unsigned int bar( unsigned int n ) { return n*3 + 1 ; }
unsigned int alt_bar( unsigned int n ) { return n+n+n + 1 ; }
unsigned int palooka_bar( unsigned int n ) { return ( (n<<2) - n ) + 1 ; }
unsigned int palooka2_bar( unsigned int n ) { return ( (n<<1) + n ) + 1 ; }
|
https://godbolt.org/g/ye8cmB
It is possible that the attempted 'clever' code may result in suboptimal machine code; as in the case of
palooka_bar here; optimisers find it easier to optimise transparent code.
https://godbolt.org/g/fHibQu
While learning C++, it is important to cultivate good programming habits; basic programming hygiene.