Question

In the IAR C/C++ Compiler manual, it states for writing optimization-friendly source code:

Avoid taking the address of local variables using the & operator. This is inefficient for two main reasons. First, the variable must be placed in memory, and thus cannot be placed in a processor register. This results in larger and slower code. Second, the optimizer can no longer assume that the local variable is unaffected over function calls.

What other methods are there of taking an address of a local variable? Obviously I know that if I had a pointer to that variable I could use that, and if I had an array I could use the array name, however I am not aware of any other methods to take the address of a local variable other than the & operator.

Was it helpful?

Solution

There are no other ways to take the address[*]. The text "using the & operator" in that advice is redundant. I suppose it's just there to remind you which operator is the address-of operator, in case you weren't clear what you're supposed to avoid using.

The optimizations that it's talking about are:

1) if you don't take the address, then the variable doesn't need to have an address.

2) if the address never "escapes" code that the compiler can see, then the compiler can assume the value doesn't change via code that it can't see. Not taking the address ensures this, but in some cases compilers can do escape analysis even when the address is taken.

It really doesn't matter for either of these purposes how the address is taken, so if there were another way to take the address in C, then the advice would have to mention it alongside the & operator.

[*] [Edit: aha! I'm slightly wrong. If the variable is an array then you can take its address without using the & operator, just let it decay to a pointer-to-first-element. I don't know whether or not the IAR compiler actually optimizes sufficiently small arrays into registers, if not then there's no need to mention it. But it's certainly allowed to.]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top