How many styles of writing functions are there in C?

后端 未结 4 1997
-上瘾入骨i
-上瘾入骨i 2021-01-13 00:03

So far, I know two styles:

/* 1st style */
int foo(int a) {
return a;
}

/* 2nd style */
int foo(a)
int a;
{
return a;
}

(I saw someone wri

相关标签:
4条回答
  • 2021-01-13 00:15

    The 2nd one is K&R C style syntax, but it is obsolete now. Checkout @Basile Starynkevitch's answer.

    0 讨论(0)
  • 2021-01-13 00:22

    The second style is the older style and is supported for backwards compatibility. I don't know of any other styles off the top of my head, but you should use the first (newer) style. The second (older) style was already deprecated when I started working with C (1994).

    0 讨论(0)
  • I won't call these styles, but languages variants (or dialects).

    A coding style is a set of optional conventions that might not be followed. For instance, some coding styles request that macro names are all capitals (but your code will compile if you don't follow that rule).

    Your "2nd style" is called Kernighan & Ritchie C. It is the old C defined in the late 1970s (in the very first edition of a famous book on C by Kernighan and Ritchie; subsequent editions have been conforming to later C standards). It is an obsolete language.

    Current compilers are often following the C99 ISO standard (published in 1999), which has been replaced by the new C11 standard (published in 2011).

    GCC compilers are accepting the C99 standard with the -std=c99 program argument. I strongly suggest to compile with gcc -Wall -std=c99; Recent GCC compilers (ie 4.6 and 4.7) are accepting -std=c11 IIRC for the newer standard C11.

    Don't code today in the old Kernighan and Ritchie C dialect: it is obsolete, and less and less supported by compilers. IMHO C99 is a good standard to follow if you are cautious. And take profit of some of its features (in particular, ability to mix declarations and statements inside a block; older C dialects required to put all the declarations at the start of a block.).

    The standard has progressed, in particular because it added features and is more precise w.r.t. to current systems and practices (e.g. multi-core processors)

    0 讨论(0)
  • 2021-01-13 00:30

    There are (at least) two disadvantages when using the 2nd style:

    1. If the function prototype is also missing, the compiler will not check for proper argument type. And, if I remember correctly, the number of arguments will also not be checked.
    2. This (K&R, 1st Ed) style is valid only for backward compatibility ... someday, the C standard will (perhaps) disallow this style and your programs will halt.

    Also, for better readability, you can put function's return type on its own line (especially useful with long-winded return types like unsigned long int and headers):

    int 
    foo(int a) 
    {
        return a;
    }
    
    0 讨论(0)
提交回复
热议问题