Heap and Stack segment - c

I came across a small puzzle for which I was trying to find the output. Once I managed to get the output, I tweaked in 1 line and the output is totally different. Why does the output of the following two programs vary?:
a)
#include<stdio.h>
int fun()
{
static int num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
Output:
38 35 32 29 26 23 20 17 14 11 8 5 2
b)
#include<stdio.h>
int fun()
{
static int num;
num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
Output: Infinite loop printing 40 everytime
There is just one difference: The declaration and initialization are done at the same time in (a) but separately in (b). How does that effect the final outcome?

static int num = 40;
static int num;
These both get evaluated once. num does not live on the runtime stack (but rather in the data segment) Then,
num = 40;
gets evaluated every time you call fun(). You're reassigning a variable that was declared outside the stack to 40, causing it to loop forever.

In the first one, num will only be initialised to 40 the first time the function is called. In the second one, it is set to 40 every time the function is called.

first one, num gets initialized once, no matter how many times you call the function
second one, num gets set to 40 every time you call the function

Two concepts need to be looked into here
lifetime of variable
scope of variable
The lifetime of a variable is the period over which it exists. If num were defined without the keyword static, the lifetime would be from the entry into fun() to the return from fun(); so it would be re-initialized to 40 on every call.
The scope of variable is where the variable name can be seen. Here, num is visible only inside function fun().
The keyword static is used to extend the lifetime of a variable to the lifetime of the program. In case of static declaration initialization occurs only once and then the variable retains its value inside the routine fun(). So if you are overwriting it by setting it to value of 40 in the second case its values keeps getting set to 40 on every call to fun(). The declaration of the variable num as static is redundant in your second code.

Related

If a variable is defined previously and is waiting on a function to return a value, what is the value of that variable?

This is for programming in C.
Say I had the follow code in my program:
int fun1(int x);
int main (void)
{
int a = 5;
a = fun1(10);
}
int fun1(int x)
{
\\Program arbitrarily ends here
return x;
}
In my memory diagram what would the value of a be assuming the program terminates before fun1 is able to return a value? Would the value of a be undetermined (??) or would it be 5?
The value of a is already initialized to 5. Now, according to the condition, you want to know the results of that circumstance when the fun1() ends before it could return a value; assume the following:
int fun1(int x)
{
// return x;
}
Here we've supposed the function quits before returning the value.
You'll still get the output 5 before, during or after execution of the program since it returns nothing but the variable a is preassigned to 5 and it can't be changed to 10 unless the function returns 10 and assigns to the variable.
But remember, if you don't assign anything to a, then it may show an unexpected value (I got 4195638 when used printf() for a).

Not understanding the function of static int in C

I'm trying to understand this piece of code, but I don't know why the amount of a static variable sometimes changes and sometimes not.
#include <stdio.h>
int func1 (int x)
{
extern int a;
static int y=0;
printf("%d\n%d\n",a,y);
a=x+5; y=x+1;
{int y=10; printf("%d\n",y);}
return y;
}
int a;
int main()
{
a=func1(1);
printf("%d\n",a);
{
int a=1;
printf("%d\n", a);
}
a=func1(a);
printf("%d",a);
return 0;
}
Here is the output:
0
0
10
2
1
2
2
10
3
At first, when a = func(1) is run, y is declared as 0 and then changes to 2 and it prints 2. But when it runs a = func(a) when a is 2, I expected that y will become 0 through static int y = 0 but y doesn't change. Why it doesn't happen?
A static object is initialized, conceptually, when it is created.
The lifetime of a static object begins when the program starts executing and continues until execution ends.
So, when the program starts executing, y is initialized to 0. After that, its value changes only when it is modified, as with assignment statements. The statement that defines it, static int y = 0;, does not modify it after the initialization.
Variables declared as static inside of a function retain their value through the lifetime of the program, even when the variable name goes out of scope. The initializer for a static variable is only applied at program startup.
So when the program starts, y is initialized to 0. Then in the first call to func it sets y to 2. This value is retained even after the function exits. So when func is called a second time, y is still 2 when the function starts.
static means you have only one shared value of the variable, you can imagine it declared as a global variable keeps its value between multiple function calls.
First times you called the funct1 with x = 1 so y returned as 2.
The next time you called the function func1 with x = 2, the value of y will not be declared again but will use the last value of last call (y=2), and update it with y = x + 1 to be 3.
TLDR;
Read the static declaration of a variable only once (static int y = 0), and do not back to it again, use the last value of it next times.

Why is the output of the following two segments different?

#include <stdio.h>
int main()
{
static int i = 5; // here
if (--i){
printf("%d ", i);
main();
}
}
Output: 4 3 2 1
#include <stdio.h>
int main()
{
int i = 5; // here
if (--i){
printf("%d ", i);
main();
}
}
Output: 4 4 4 4... (Segmentation fault)
Any idea how static int variable is taken into account only once and int is taken over and over again?
When you declare a static variable in a function, the function "remembers" the last value of the variable even after it terminates.
void Foo() {
static int x = 5;
}
In the example above, you are telling the compiler that x shall be "remembered" and has an initial value of 5. Subsequent calls to Foo() does not reassign x a value of 5, but uses the previously remembered value.
In contrast:
void Bar() {
int x = 5;
}
Here, you are telling the compiler that everytime Bar() executes, a new variable x is to be created on the stack and assigned a value of 5.
A variable declared as static inside of a function retains its value each time the function is called. It is initialized only once, when the function is first called. So when the function calls itself the value of i is retained from the prior call.
A local variable that is not static is specific to a given call of a function, so each time the function is called a new copy of the variable is created and initialized. This results in i being 5 each time, which in turn results in infinite recursion leading to a stack overflow and a core dump.

Can any one explain scope of c-macro's defined local to function and global?

I don't know why this output appears and behavior of pre-processor.
Output:
the value in main 10
the value in fun 20
the value in 2 main 10
Source
#include<stdio.h>
#define MAX 10
int fun(int a);
int main()
{
int a;
a=MAX;
printf("the value in main =%d\n",a);
fun(a);
int b;
b=MAX;
printf("the value in 2 main =%d\n",b); /*<----doubt at this line*/
}
What's happening when we assign new value to the macro inside local function why it is not updating outside of function?
int fun(int a)
{
#undef MAX
#define MAX 20
a=MAX;
printf("the value in 2 main =%d\n",a);
}
A macro is not checked at runtime. It is checked during before compilation, in a stage called pre-processing.
So, the compiler processes the main function first and replaces MAX with 10 in all lines. Then when it reaches the fun function, it undefines MAX and redefines it with 20, and replaces the lines in fun with 20.
For sure, you have written the code for the fun function after the main one.
The compiler changes the defined macros for its corresponding values in the order it find them in the source code, not in the execution order.

Multiple definitions for a variable

Why doesn't the following code give an error as i is defined multiple times as int i=10? Further,why isn't the iterating variable i affected? Why is there no conflict ? The output is 1010101010. How?
#include<stdio.h>
int main()
{
int i;
for(i=0;i<5;i++)
{
int i=10;
printf("%d",i);
i++;
}
}
Automatic variables are alive only in the scope {,} in which they reside.
You have two variables named i in your program:
The i declared in main has scope of entire main function.
While the i inside the for loop has scope only inside the loop.
Note that when you refer i inside the for loop the inner i shadows the i declared in the main.
int i=10; in for loop is only available inside the loop it doesn't know if it was previously defined outside the loop.
Scope of variable defined within a block of code is limited to that block only.
ie.,
int i=1;//outer i
{
int i=2;//inner i
printf("%d"&i);// this ll print 2
}
printf("%d"&i);// this ll print 1
same in for too., ie
int i=1;
for (int i=0;i<4;i++){
printf("%d",&i); // print 0 1 2 3
}
printf("%d",&i); // print 1
In your case every time you initializing inner i to 10 and printing it then you incremented inner i, so it everytime prints value of inner i you declared and initialized to 10
this is because of scope of variable
scope of variable lies within { to }
your first int i will be alive through out the main() while the int i inside for will be alive inside for loop only.
now why the output is 1010101010???
the simple explanation is when you enter for look your new i will be equal to 10, you print it then i++ makes it 11. again next time i = 10 you print it and i++ makes it 11 this continues for main() int i < 5 so five times you will get 1010101010.
hope it helps.....

Resources