c语言中和形式参数同名的情况
001、函数体内的变量名不可以和形参同名
a、
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c #include <stdio.h> int max(int a, int b) { int k = 100; return a > b ? a:b; } int main(void) { int x = 10, y = 30; printf("larger: %d\n", max(x,y)); return 0; } [root@PC1 test]# gcc test.c -o kkk [root@PC1 test]# ls kkk test.c [root@PC1 test]# ./kkk larger: 30
b、
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c #include <stdio.h> int max(int a, int b) { int b = 100; // 函数体内的变量名和形参同名导致无法编译 return a > b ? a:b; } int main(void) { int x = 10, y = 30; printf("larger: %d\n", max(x,y)); return 0; } [root@PC1 test]# gcc test.c -o kkk test.c: In function ‘max’: test.c:5:13: error: ‘b’ redeclared as different kind of symbol 5 | int b = 100; | ^ test.c:3:20: note: previous definition of ‘b’ with type ‘int’ 3 | int max(int a, int b) | ~~~~^
002、函数调用时的实参可以和形参同名。
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c #include <stdio.h> int max(int a, int b) { return a > b ? a : b; } int main(void) { int a = 10, b = 50; printf("larger: %d\n", max(a,b)); // 函数调用的实参跟函数定义时的形参同名,对函数无影响 return 0; } [root@PC1 test]# gcc test.c -o kkk [root@PC1 test]# ls kkk test.c [root@PC1 test]# ./kkk larger: 50
。
003、不同函数的形参可以同名
test.c [root@PC1 test]# cat test.c #include <stdio.h> int max2(int a, int b) { return a > b ? a:b; } int max3(int a, int b, int c) // 不同函数的形参可以是同名的, 比如这里的max2和max3函数的形参a和b { int max = a; if(max < b) {max = b;}; if(max < c){max = c;};return max; } int main(void) { int a, b, c; printf("a = "); scanf("%d", &a);printf("b = "); scanf("%d", &b);printf("c = "); scanf("%d", &c); printf("the large between a and b is %d\n", max2(a,b)); printf("the largest among a, b, and c is %d\n", max3(a,b,c));return 0; } [root@PC1 test]# gcc test.c -o kkk [root@PC1 test]# ls kkk test.c [root@PC1 test]# ./kkk a = 34 b = 546 c = 345 the large between a and b is 546 the largest among a, b, and c is 546 [root@PC1 test]# ./kkk a = 35 b = 566 c = 3255 the large between a and b is 566 the largest among a, b, and c is 3255
。