1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
#include <stdio.h> #include <stdlib.h> #include <string.h> void static_counter (){ static int n; // Static locals automatically initialized as 0. printf("static_counter value: %d\n", n++); } void stack_counter (){ int n = 0; printf("stack_counter value: %d\n", n++); } void heap_counter (){ int *n; n = (int *)malloc(sizeof(int)); *n = 0; printf("heap_counter value: %d\n", (*n)++); free(n); } int main(){ static_counter(); static_counter(); static_counter(); stack_counter(); stack_counter(); stack_counter(); heap_counter(); heap_counter(); heap_counter(); } // Output: // static_counter value: 0 // static_counter value: 1 // static_counter value: 2 // stack_counter value: 0 // stack_counter value: 0 // stack_counter value: 0 // heap_counter value: 0 // heap_counter value: 0 // heap_counter value: 0 |