Search code examples
assemblyx86masmcalling-convention

Are local variables necessary?


My understanding is the C calling convention places arguments on the stack prior to calling a function. These arguments could be accessed within the function through explicit stack parameters using EBP as a reference such as [EBP + 8] or [EBP + 12].

My question is if it could be accessed this way, why are local variables necessary? - couldn't a function just work with the arguments directly? Is it just for cases where the function has no parameters, but still initializes local variables for internal use?


Solution

  • Quite often, functions need to remember more data than just the parameters. For example, consider this function counting the number of set bits in its argument:

    int popcount(int k)
    {
        int count = 0;
    
        while (k != 0) {
            k &= k - 1;
            count++;
        }
    
        return (count);
    }
    

    In addition to the parameter, we also need to remember how many bits we saw. Thus, a local variable is required.