c Code error multiplying the language number.

Asked 2 years ago, Updated 2 years ago, 30 views

It's a code that goes up by multiplying the number. The code below is printed. There's an error code somewhere. Which part should I fix? Code must not be added.

"Code"

void one(void);

void two(void);

int times = 0;

void one() { int times = 0;

times++;
printf("one():  ");
printf("one() or two() have been called a total of %d times\n", times);

}

void two() { static int times = 0;

times++;
printf("two():  ");
printf("one() or two() have been called a total of %d times\n", times);

}

int main() {

printf("\n");
one();  // 1 time
one();  // 2 times
two();  // 3 times
one();  // 4 times
two();  // 5 times
two();  // 6 times
one();  // 7 times
one();  // 8 times
two();  // 9 times
printf("\n");

exit(0);

}

"Code"

c

2022-09-22 14:16

1 Answers

If the comment in the main sentence should be printed as gday said in the comment above, Clear one() function's int times = 0 and clear two() function's static int times = 0.

void one() {
    // // int times = 0;
    times++;
    printf("one():  ");
    printf("one() or two() have been called a total of %d times\n", times);
}

The int times of the one() function is a region variable, and when the region variable and the global variable have the same name, inside the function, ignore the global variable times and check the region variable.

Therefore, each time a function called one() is called, times is initialized to zero and then becomes a ++ action, so if int times = 0 is not deleted, the result of the one() function will always be 1.

So if you delete the int times declaration in the one() function, the global variable times is ++.

void two() {
    // // static int times = 0;
    times++;
    printf("two():  ");
    printf("one() or two() have been called a total of %d times\n", times);
}

Static int times is a static variable that is created at the start of the program and does not disappear after the function is called.

ps.

It is a static variable and it is declared in the two() function, so it has the same characteristics of the local variable.

Therefore, calling the two() function will only ++ the regional function times generated when the program is run, and the times will not disappear due to the nature of the static variable after the function is called, so the value of the regional variable times will continue to increase.

So if you clear the declaration static int times, the two() function also becomes a function that does the ++ action of the global variable times, so you get the same result as the main() statement of the question.


2022-09-22 14:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.