This C function should always return false, but it doesn’t

后端 未结 4 1812
天命终不由人
天命终不由人 2021-01-29 18:15

I stumbled over an interesting question in a forum a long time ago and I want to know the answer.

Consider the following C function:

f1.c

#incl         


        
4条回答
  •  [愿得一人]
    2021-01-29 18:27

    As noted in other answers, the problem is that you use gcc with no compiler options set. If you do this, it defaults to what is called "gnu90", which is a non-standard implementation of the old, withdrawn C90 standard from 1990.

    In the old C90 standard there was a major flaw in the C language: if you didn't declare a prototype before using a function, it would default to int func () (where ( ) means "accept any parameter"). This changes the calling convention of the function func, but it doesn't change the actual function definition. Since the size of bool and int are different, your code invokes undefined behavior when the function is called.

    This dangerous nonsense behavior was fixed in the year 1999, with the release of the C99 standard. Implicit function declarations were banned.

    Unfortunately, GCC up to version 5.x.x still uses the old C standard by default. There is probably no reason why you should want to compile your code as anything but standard C. So you have to explicitly tell GCC that it should compile your code as modern C code, instead of some 25+ years old, non-standard GNU crap.

    Fix the problem by always compiling your program as:

    gcc -std=c11 -pedantic-errors -Wall -Wextra
    
    • -std=c11 tells it to make a half-hearted attempt to compile according the (current) C standard (informally known as C11).
    • -pedantic-errors tells it to whole-heartedly do the above, and give compiler errors when you write incorrect code which violates the C standard.
    • -Wall means give me some extra warnings that might be good to have.
    • -Wextra means give me some other extra warnings that might be good to have.

提交回复
热议问题