My code below is trying to output the next power of 2 when the program is run, so ./powers
would return 4, then if I run again, ./powers
would return 8.
However it returns 4 every time, how do I get the variable num to save its last value?
#include <stdio.h>
int powers(void) {
int num, power;
num = 2;
power = 2;
num = num * power;
printf("%d\n", num);
return 0;
}
int main(void) {
powers();
return 0;
}
CodePudding user response:
You make it persistent.
The easiest way (shortest route for a newbie) is to save it to a file and read it back from there at the start of the program, in case the file exists.
At least that is the answer to the question involving "when the program is run".
The answer for the question involving "next call of the function" is different. For that, i.e. when the program does not terminate in between and you call the function multiple times, e.g. in a loop, you can use a static variable, with the keyword static
.
A simple example of a static variable, similar to your code is:
#include <stdio.h>
int powers(void) {
int power;
static int num = 2;
power = 2;
num = num * power;
printf("%d\n", num);
return 0;
}
int main(void) {
powers();
powers();
return 0;
}
Which gets you an output of:
4
8
CodePudding user response:
An alternative way to make a value 'persistent' is to define the variable "at a higher, longer-lasting" level.
Below, the value of 'val' is copied, passed to the function where the copy is modified (and printed), and the modified value is returned to the calling location. The modified value replaces the previous value. The value 'survives' for the duration of the function where it is defined; in this case main()
.
int powers( int val ) {
int power = 2;
val = val * power; // only true for powers of two
printf( "%d\n", val );
return val;
}
int main() {
int val = 2;
val = powers( val );
val = powers( val );
val = powers( val );
return 0;
}