代码到底怎么了
下面是修改后的代码,他们的确改了不少东西。
#include <stdio.h>
float total = 0.0;
short count = 0;
/* 6%,比我的经纪人拿的少多了…… */
short tax_percent = 6;
int main()
{
/* 嘿,我将和梁朝伟联袂出演一部电影 */
float val;
printf("Price of item: ");
while (scanf("%f", &val) == 1) {
printf("Total so far: %.2f\n", add_with_tax(val));
printf("Price of item: ");
}
printf("\nFinal total: %.2f\n", total);
printf("Number of items: %hi\n", count);
return 0;
}
float add_with_tax(float f)
{
float tax_rate = 1 + tax_percent / 100.0;
/* 小费呢?口头传授也是要收费的 */
total = total + (f * tax_rate);
count = count + 1;
return total;
}
他们先是加了一些注释,然后改变了两个函数的先后顺序,仅此而已。
不应该有问题吧,代码应该可以正常工作,你说呢?一切都很顺利,直到他们编译了代码……
试驾
打开控制台编译程序,下面的情况发生了:
糟糕。
不妙。error: conflicting types for 'add_with_tax'
是什么意思?什么是previous implicit declaration?为什么编译器认为add_with_tax
是int
?它不应该返回浮点数么?
编译器会忽视注释,加不加都一样,所以问题是由改变函数的顺序所引起的。既然是顺序问题,为什么编译器不返回一条这样的消息:
说真的,为什么这时编译器不帮帮我们?
为了理解到底发生了什么,需要进入编译器的灵魂深处,站在它的立场看问题。你会发现编译器不但想帮忙,而且帮过了头。