There are several coding operations that (I suspect) most compilers will change into more efficient operations at the assembly or machine code level. I have several questions about whether or not the compiler does any of this work, and if it's even best for the compiler to automatically do so.
(Note: These examples use C and C-like language syntax. However, just because i'm doing examples in C, doesn't mean I only want answers for the C compilers. I'm interested in how most major languages handle these things.)
The first is
a += 1; vs
a is any integer variable. Both these codes ultimately result in the same thing (incrementing by 1), but
a++ does it quicker somehow. I was self-taught for my first few languages and just never came across the
a++ style, so I use the
a += 1 style in all my private programming. However, of course later I discovered that
a++ is more common when you only need to increment by 1. I believe the origins of it are from the old days where computers were super slow, therefore finding a shortcut for incrementing (or decrementing) by 1 was a huge deal. Now don't get me wrong, it could still make a difference today like in huge nested loops, and the most common place i see the shortcut is in loops anyway. Is there any reason why you would strictly want the slower
a += 1 style? Incidentally, do most compilers automatically translate a
a += 1 into a
The second is dividing by a power of 2.
b /= 8; can be shortcut to a simple bit shift by 3 bits to the right (towards the least significant bit, and filling in zeros on the MSB side)---as long as
b is an integer. Should compilers make this translation, or is there some instance where you want the slower
b /= 8 operation? Do compilers typically optimize this?
Can't think of any more simple types of shortcuts, but wouldn't be surprised if some exist.