CodeBlocks下C语言出现函数隐式声明警告及修改后函数不执行问题
问题原因
- 第一个版本出现
Implicit Declaration of Function警告的原因:addition函数定义在start函数之前,addition内部调用start时,编译器还没有扫描到start的定义,也没有提前看到start的函数声明,所以触发隐式声明警告。C语言旧标准会默认将未声明的函数返回值视为int,和你实际start函数的void返回值不匹配,虽然碰巧执行成功,但属于未定义行为。 - 第二个版本函数无法执行的原因:你把
addition函数末尾原本的start();函数调用,错误替换成了void start();函数声明,相当于你没有执行调用逻辑,只是在局部声明了一个函数原型,自然不会触发start的执行。 - 额外隐藏bug:
start函数中scanf("%s", &ope);写法错误,ope是单字符变量,%s用于读取字符串,会导致缓冲区溢出,大概率会触发程序崩溃或异常行为。
修复方案
正确的做法是在所有函数定义之前,提前声明所有用到的函数原型,修改后的代码示例如下:
#include <stdio.h> #include <conio.h> #include <stdlib.h> // 提前声明函数原型,解决隐式声明问题 void start(); void addition(); void addition(){ int vala, valb, resu; system("cls"); printf("SiMPLE CALCULATOR 1.0a\n"); printf("ADDITION\n"); printf("\n"); printf("Enter the first value of addend: "); scanf("%d", &vala); printf("Enter the second value of addend: "); scanf("%d", &valb); resu=vala+valb; printf("The sum of %d and %d is: %d\n", vala, valb, resu); printf("PRESS [ANY KEY] TO CONTINUE..."); getch(); start(); // 保留函数调用,不要改成声明 } void start(){ char ope; system("cls"); printf("SiMPLE CALCULATOR 1.0a\n"); printf("What operation will be used:"); // 把%s改成%c,匹配char类型,前面加空格吃掉之前的换行符 scanf(" %c", &ope); if (ope == 'a'){ addition(); }else if (ope == 'b'){ printf("bbbbbbbbbbbb\n"); }else{ printf("ccccccccccc\n"); } } int main(){ int choices; printf("SiMPLE CALCULATOR 1.0a\n"); printf("choose an option:"); scanf("%d", &choices); if (choices == 1){ start(); } getch(); return 0; }
内容的提问来源于stack exchange,提问作者Pyromagne
相关产品推荐
相关产品推荐

