代码到底怎么了

下面是修改后的代码,他们的确改了不少东西。

  1. #include <stdio.h>
  2. float total = 0.0;
  3. short count = 0;
  4. /* 6%,比我的经纪人拿的少多了…… */
  5. short tax_percent = 6;
  6. int main()
  7. {
  8. /* 嘿,我将和梁朝伟联袂出演一部电影 */
  9. float val;
  10. printf("Price of item: ");
  11. while (scanf("%f", &val) == 1) {
  12. printf("Total so far: %.2f\n", add_with_tax(val));
  13. printf("Price of item: ");
  14. }
  15. printf("\nFinal total: %.2f\n", total);
  16. printf("Number of items: %hi\n", count);
  17. return 0;
  18. }
  19. float add_with_tax(float f)
  20. {
  21. float tax_rate = 1 + tax_percent / 100.0;
  22. /* 小费呢?口头传授也是要收费的 */
  23. total = total + (f * tax_rate);
  24. count = count + 1;
  25. return total;
  26. }

他们先是加了一些注释,然后改变了两个函数的先后顺序,仅此而已。

不应该有问题吧,代码应该可以正常工作,你说呢?一切都很顺利,直到他们编译了代码……

代码到底怎么了 - 图1试驾

打开控制台编译程序,下面的情况发生了:

代码到底怎么了 - 图2

糟糕

不妙。error: conflicting types for 'add_with_tax' 是什么意思?什么是previous implicit declaration?为什么编译器认为add_with_taxint?它不应该返回浮点数么?

编译器会忽视注释,加不加都一样,所以问题是由改变函数的顺序所引起的。既然是顺序问题,为什么编译器不返回一条这样的消息:

代码到底怎么了 - 图3

说真的,为什么这时编译器不帮帮我们?

为了理解到底发生了什么,需要进入编译器的灵魂深处,站在它的立场看问题。你会发现编译器不但想帮忙,而且帮过了头。