這是一個遞歸函數調用的例子。程序中函數f o r w a r d _ a n d _ b a c k w a r d s ( )的功能是顯示一個字符串后反向顯示該字符串。 [例4-17] 計算1~7的平方及平方和。 #include <stdio.h> # include<math.h> void header(); / *函數聲明* / void square(int number); void ending(); int sum; /* 全局變量* / m a i n ( ) { int index; h e a d e r ( ) ; / *函數調用* / for (index = 1;index <= 7;i n d e x + + ) s q u a r e ( i n d e x ) ; e n d i n g ( ) ; / *結束* / } void header() { sum = 0; /* 初始化變量"sum" */ } void square(int number) { int numsq; numsq = number * numbe;r sum += numsq; printf("The square of %d is %d/,nn"u m b e r ,nu m s q ) ; } void ending() { printf("/nThe sum of the squares is %d,/ns"u m ) ; } 運行程序: R U N ¿ This is the header for the square program The square of 1 is 1 The square of 2 is 4 The square of 3 is 9 The square of 4 is 16 The square of 5 is 25 The square of 6 is 36 The square of 7 is 49 The sum of the squares is 140 這個程序打印出1到7的平方值,最后打印出1到7的平方值的和,其中全局變量s u m在多個 函數中出現過。 全局變量在h e a d e r中被初始化為零;在函數s q u a r e中,s u m對n u m b e r的平方值進行累加,也就是說,每調用一次函數s q u a r e和s u m就對n u m b e r的平方值累加一次;全局變量s u m在函數 e n d i n g中被打印。 [例4-18] 全局變量與局部變量的作用。 #include <stdio.h> void head1(void); void head2(void); void head3(void); int count; /* 全局變量* / m a i n ( ) { register int index; / *定義為主函數寄存器變量* / h e a d 1 ( ) ; h e a d 2 ( ) ; h e a d 3 ( ) ; for (index = 8;index > 0;index--) /* 主函數"for" 循環* / { int stuff; /* 局部變量* / /* 這種變量的定義方法在Turbo C 中是不答應的* / /* stuff 的可見范圍只在當前循環體內* / for(stuff = 0;stuff <= 6;s t u f f + + ) printf("%d ",s t u f f ) ; printf(" index is now %d/,n"in d e x ) ; } } int counter; /* 全局變量* / /* 可見范圍為從定義之處到源程序結尾* / void head1(void) { int index; / * 此變量只用于head1 */ index = 23; printf("The header1 value is %d/,n"in d e x ) ; } void head2(void) { int count; /* 此變量是函數h e a d 2 ( ) 的局部變量* / /* 此變量名與全局變量c o u n t 重名* / /* 故全局變量c o u n t 不能在函數h e a d 2 ( ) 中使用* / count = 53; printf("The header2 value is %d/,n"co u n t ) ; counter = 77; } void head3(void) { printf("The header3 value is %d/,nc"o u n t e r ) ; } 運行程序: R U N ¿ The headerl value is 23 The header2 value is 53 The header3 value is 77 0 1 2 3 4 5 6 index is now 8 0 1 2 3 4 5 6 index is now 7 0 1 2 3 4 5 6 index is now 6 0 1 2 3 4 5 6 index is now 5 0 1 2 3 4 5 6 index is now 4 0 1 2 3 4 5 6 index is now 3 0 1 2 3 4 5 6 index is now 2 0 1 2 3 4 5 6 index is now 1 該程序的演示幫助讀者來了解全局變量、局部變量的作用域,請仔細理解體會。