yigggit
yigggit

Reputation: 1

preserved value of a variable in C

#include <stdio.h>
#include <stdlib.h>

void func(int i);

int main() {


int i;
for(i=0;i<3;i++){
    func(i);
}
return 0;
}

void func(int i){

int k;


if(i==0){

    k=4;
}

printf("%d\n",k);

Sample Run:

4
4
4

Can someone please explain how come k is always equal to 4. Everytime I call the function I am redefining k and how can the value of k be preserved everytime I call the function

Upvotes: 0

Views: 1456

Answers (3)

too honest for this site
too honest for this site

Reputation: 12263

Your current code exhibits undefined bahaviour (there might be demons flying out of your nose), as k is not initialized. Any value you actually read is invalid (technically: whatever is at its current memory location). Rason is that local variables are not initialized by default for performance reasons.

So, if you do not want that, you have to explictily initialize it by an initial assignment. This may be included in the definition as for any other variable, but with a non-constant expression.

If you want to keep the last value of k, you have to define it static. Note that any initialization is done when the program loads and it does preserve its value between calls. Thus, the initialization has to be a constant expression If you do not explicitly initialize it, it defaults to 0.

Upvotes: 1

Miguel Hernando
Miguel Hernando

Reputation: 63

If you want to preserve the value of K but into the local scope of the function you could use the static type modificator.

static int k=0;

thus, your variable is global from the point of view of duration, but its scope is local to the function or block where it is initialized.

And yes,.. probably the function reuses the same location of k, because you do not initialize its value as Buddy points out.

Upvotes: 1

Buddy
Buddy

Reputation: 11028

You're not initializing k either... so it's probably just re-using the same memory location each time you call the function and it just happens to still be 4 from the first call...

Try this int k = 0;

Upvotes: 2

Related Questions