たとえば"add"
、int を消費して の値を"a"
生成する ftn という呼び出しを書くと、最後に呼び出されたものによって生成される値です。例えばa + b
b
add(1) ==> 1 (first called b=0,then 1 + 0 = 1)
add(2) ==> 3 (second called b=1, then 2 + 1 = 3)
add(4) ==> 7 (third called b=3, then 3 + 4 =7)
編集:「静的」を使用しなくても
たとえば"add"
、int を消費して の値を"a"
生成する ftn という呼び出しを書くと、最後に呼び出されたものによって生成される値です。例えばa + b
b
add(1) ==> 1 (first called b=0,then 1 + 0 = 1)
add(2) ==> 3 (second called b=1, then 2 + 1 = 3)
add(4) ==> 7 (third called b=3, then 3 + 4 =7)
編集:「静的」を使用しなくても
なぜ静電気がないのですか?それはまさにあなたが必要とするものですよね?それ以外の場合は、パラメーターをポインターとして渡し、必要な場所で変更できます。
void f( int * a )
{
*a += 5;
}
そしてメイン、またはあなたが呼ぶところならどこでも
int a = 0;
f( &a );
f( &a );
a
は 10 になり、関数で操作することもできます。
これは役に立ちましたか?
これはあなたが望むことをしますか?
int add(int a) {
static int b = 0;
return b += a;
}
static 変数b
はadd()
関数に対してローカルですが、呼び出し間でその値を保持します。
静的ローカル変数はどうですか?
int add(int a)
{
static int b = 0;
b += a;
return b;
}
または多分ラムダ:
int main(int,char**)
{
int b = 0;
auto add = [&](int a) { b += a; return b; };
std::cout << add(1) << "\n";
std::cout << add(2) << "\n";
std::cout << add(4) << "\n";
return 0;
}
出力:
1
3
7
#include <stdio.h>
int add(int value){
FILE *fp;
int pv = 0;
fp = fopen("temp.bin", "r+b");
if(fp==NULL){
fp = fopen("temp.bin", "wb+");
fwrite(&pv, sizeof(int), 1, fp);
rewind(fp);
}
fread(&pv, sizeof(int), 1, fp);
pv += value;
rewind(fp);
fwrite(&pv, sizeof(int), 1, fp);
fclose(fp);
return pv;
}
int main() {
printf("%d\n", add(1));
printf("%d\n", add(2));
printf("%d\n", add(4));
return 0;
}
検討:
#include <stdio.h>
int test1(){
static int localVar=0;
localVar++;
printf("test1 %i\n",localVar);
}
int test2(){
static int localVar=0;
localVar++;
printf("test2 %i\n",localVar);
}
int main(){
test1();
test2();
test1();
}
このプリントを実行する
test1 1
test2 1
test1 2
static は変数が定義されているスコープ内の変数に適用されるため、この場合、test1 内と test2 内の両方で、両方とも値 0 から始まり、関数が呼び出されるたびにインクリメントされます。 test1 への最初の呼び出しでは、test2 内の値はインクリメントされていません。test1 を再度呼び出すと、値が記憶されていることがわかります。確信が持てない場合は、それぞれの呼び出し回数を調整して、自分で試してみてください。
状態を維持する必要があるが、関数がそれを変数に格納したくない場合は、static
選択肢が限られています。
たとえば、次のように状態を渡すだけです。
/* Be careful with the first call - the caller must initialise
previous_result to 0 */
int add(int a, int *prev_result)
{
int result = a + *prev_result;
*prev_result = result;
return result;
}
または、次のようにファイルに保存することもできます。
/* Incomplete, and completely untested! */
int add(int a)
{
FILE *state_file;
int result
int prev_result;
state_file = fopen("state.txt", "r");
prev_result = get_value_from_file(state_file); /* write this yourself */
fclose(state_file);
result = a + prev_result;
state_file = fopen("state.txt", "w");
write_value_to_file(state_file, result); /* write this yourself */
fclose(state_file);
return result;
}