1
$\begingroup$

The below program will read a positive integer from keyboard and print the binary equivalent. This program is using only one variable.

If global variables are not stored in frame stack, how this is working.

#include<stdio.h>
int n;
void binary(n)
{
    if(n>0)
    {
        binary(n/2);
        printf("%d",n%2);
    }
}

void main()
{
    scanf("%d",&n);
    binary(n);
}
$\endgroup$
1
$\begingroup$

The program is actually using two variables. There is a global variable n, which is used by main(). There is a local variable, confusingly also named n, which is used by binary() and allocated on the stack.


Here are some excerpts from the code generated on my machine:

_binary:
...
        movl    %edi, -4(%rbp)
        cmpl    $0, -4(%rbp)
...

_main:
...
        movq    _n@GOTPCREL(%rip), %rsi
        movl    (%rsi), %edi
        movl    %eax, -4(%rbp)          ## 4-byte Spill
        callq   _binary
...
        .comm   _n,4,2                  ## @n

The first excerpt contains part of the code generated for binary(). The parameter n is passed in the register edi, and is then stored on the stack. The following command compares it to zero, implementing part of n>0.

The second excerpt contains part of the code generated for main(). The global variable n is allocated as a common symbol. The excerpt consists of the function call binary(n). You can see that n is pulled out of the global storage and put into edi, before calling binary().

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.