Exercise on storage class

Guess the output #1

#include <stdio.h>

int main()
{
	int score = 98;

	static int new_score = score;

	printf("total: %d\n", new_score);

	return 0;
}

Compiling this code produces following output, click on below icon to see the output.

program.c: In function ‘main’:
program.c:7:32: error: initializer element is not constant
     7 |         static int new_score = score;
       |                                ^~~~~

Explanation: on 5th line, score is an auto variable. on 6th line, new_score is and static variable. static variables are load time entity while auto variable are run time entity. so we can't assign any run time variable to load time variable. In other words, static variable gets memory at compile time while auto variable gets memory at run time.

Guess the output #2

#include <stdio.h>
#include <string.h>

char *foo()
{
	static char str[12];
	
	return str;
}

int main()
{ 
	char *var = "from earth";

	strcpy(foo(), var);

	var = foo();

	strcpy(var, "from mars");

	printf("%s\n", foo());

	return 0;
}

Compiling this code produces following output. click on below icon to see the output.

from mars

Explanation: None.


©2023-2024 rculock.com