Home > front end >  How static modifier works in C?
How static modifier works in C?

Time:06-08

I am trying to understand how the "static" modifier works in C, I went looking for its meaning and everything I found seemed a bit vague.

It is a modifier to allow the values of a variable to exist until the end of the program execution.

I understood what it means and its purpose, but beyond this definition I wanted to understand how it works underneath, so I generated the assembly of the C code

char    *thing(char *a)
{
    char *b;

    b = malloc(3);

    b[0] = 'y';
    b[1] = '\0';
    return (b);
}

char    *some(int fd)
{
    static char *a = "happened";
    a = thing(a);
    return (a);
}

I create another code with non-static a variable and got this

/* With static variable */
    .file   "static_test.c"
    .text
    .globl  thing
    .type   thing, @function
thing:
.LFB6:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $32, %rsp
    movq    %rdi, -24(%rbp)
    movl    $3,            
  • Related