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
。
分类:
c/c++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-11-07 centos7 中安装perl的JSON模块
2023-11-07 Configuration failed because libxml-2.0 was not found. Try installing:
2023-11-07 Configuration failed to find one of freetype2 libpng libtiff-4 libjpeg.
2023-11-07 Configuration failed because libcurl was not found. Try installing:
2023-11-07 ERROR: dependencies ‘openssl’, ‘curl’ are not available for package ‘credentials’
2023-11-07 fatal error: pango/pangocairo.h: No such file or directory
2023-11-07 linux(redhat系列 rpm软件管理)中确认是否安装指定的安装包