I was trying to assign a value to a location outside of an array in a demo program in C. The array was of type int
, and I was expecting it to overflow into the next variable I had declared, b
. However, after running the program, my shell returned 1 and aborted. When I added the static
keyword to the array and the integer, the program allowed me to print the value of the variable, b
. However, I’m not sure why. What does the static keyword do in this context, and what difference does it make?
Take this piece of code:
#include <stdio.h>
int main(void)
{
int a[4];
int b;
a[4] = 42;
printf("%i\n", b);
}
When I run it, the program outputs 1\n zsh:abort ./memory
and exits.
However, when I modify it to be the following:
#include <stdio.h>
int main(void)
{
static int a[4];
static int b;
a[4] = 42;
printf("%i\n", b);
}
The program now outputs 42
. I have heard that the static keyword can have multiple uses in C, but what is it doing here that changes the program’s behavior? I have looked at many definitions and still don’t get it 🙁
You need to sign in to view this answers
Leave feedback about this