This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

C variable reuse

For C6000 Linear Assembly, it was suggested that register symbols should be used for only one thing. The quote, if I remember correctly was, "Use register symbols like Kleenex, use them only once." In this way, the Assembly Optimizer would not be confused by reusing the register symbol; that is, it wouldn't mistake the reuse of the symbol as a definition of dependency between one use of the symbol versus another.

I was asked today if this hint has any relevance to the C compiler. Would there be any optimization benefit by using different variables for different information, versus trying to be "clever" and reuse a variable for multiple data throughout a function (or program).

Obviously, one would have to balance the use of additional variables against the potential increase in data size, but using a few more local variables in a function would most likely be negligible.

Just curious,
Scott

  • Linear assembly register symbols are exactly analogous to function-local variables in C, so the same advice applies.

    If you use any level of optimization at all, the compiler will do its best to keep local variables in registers instead of using stack space, and will do a great job of re-using the registers when the variable is no longer needed.  Thus, from an optimization point of view, there is no need to re-use any variable. 

    However, the optimizer is usually very good at finding separate "lifetimes" of a variable, where a variable at different times contains values computed and used in disjoint code.  In such a case, it will split the variable into two distinct variables for you.  Sometimes the compiler won't be able to figure it out, such as a very complicated pointer expression.  The admonition to use variables only once is most important as a convenience to the programmer, as it helps you see more clearly what code is relevant to a particular variable.  You should still follow the advice, it's good programming practice.

    As to being "clever," remember that the compiler has to be very sure it understands the code before it can perform optimizations.  If you get too clever, the compiler may get confused, and you may get worse code than the "non-clever" version.