Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Keeping values intact in function 1

Status
Not open for further replies.

countdrak

Programmer
Jun 20, 2003
358
US
I have a function which is called several times, and I want the variables declared in the function to retain their values when I call the function again, without having to pass them in all the time.

Is that possible? For example, in the following code, I don't want bleh's value to be reset when I call my_func again. After the 1st iteration bleh's value is 7, and I want it to begin as 7 in the 2nd iteration.

Is there a way to do that?

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


int my_func(int x, int time);

int main()
{
	int i;
	int j;
	j= 7;
	for (i=0; i<10; i++)
	{
		my_func(j, i);
		j=j+i;
	}
	return 0;
}


int my_func(int x, int time)
{
	int bleh;


	if (time == 0)
		bleh = 0;
	
	printf("Before bleh = %d\n", bleh);

	bleh = bleh + x;
	printf("After bleh = %d\n", bleh);

	return 0;
}
 
Declare them as static. In fact, you don't even need the if statement.
Code:
int my_func(int x, int time)
{
    [COLOR=BLUE]static[/COLOR] int bleh[COLOR=BLUE] = 0[/COLOR];
[COLOR=BLUE]
    /*
    if (time == 0)
        bleh = 0;
    */[/COLOR]
    printf("Before bleh = %d\n", bleh);

    bleh = bleh + x;
    printf("After bleh = %d\n", bleh);

    return 0;
}
 
Sorry - you probably do need the if statement in case you want to reset bleh.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top