How many styles of writing functions exist in C?

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 writing codes in the second style. At first I was surprised, but the 2nd style worked (under gcc, as I tested). I was curious, and I wanted to ask this question.)

+6
source share
4 answers

I will not name these styles, but variants of languages ​​(or dialects).

An encoding style is a set of optional conventions that may not be followed. For example, some coding styles require that macro names be all capitals (but your code will be compiled if you do not follow this rule).

Your β€œ2 nd ” style is called Kernighan and Ritchie C. This is an old C, defined in the late 1970s (in the very first issue of the famous C book by Kernighan and Ritchie; subsequent editions meet later C standards). This is an outdated language.

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

GCC compilers accept the C99 standard with the program argument -std=c99 . I highly recommend compiling with gcc -Wall -std=c99 ; Recent GCC compilers (e.g. 4.6 and 4.7) accept -std=c11 IIRC for the newer C11 standard.

Do not use the code today in the old dialect of Kernighan and Ritchie C: it is deprecated and less and less supported by compilers. IMHO C99 is a good standard if you are careful. And take advantage of some of its functions (in particular, the ability to mix declarations and expressions within a block, older C dialects needed to place all declarations at the beginning of the block.).

The standard progressed, in particular, because it added functions and more precisely wrt to current systems and practices (for example, multi-core processors)

+12
source

When using the second style, there are (at least) two drawbacks:

  • If the function prototype is also missing, the compiler will not check the correct type of argument . And, if I remember correctly, the number of arguments will also not be verified.
  • This style (K & R, 1st Ed) is only valid for backward compatibility ... someday, the C standard (maybe) will prohibit this style and your programs will stop.

In addition, for better readability, you can put the return type of the function in your own string (especially useful with long return types such as unsigned long int and headers):

 int foo(int a) { return a; } 
+2
source

The second is the K & RC style syntax, but now it's deprecated. Checkout @Basile Starynkevitch answer.

0
source

The second style is an older style and is supported for backward compatibility. I don't know any other styles from the head, but you should use the first (newer) style. The second (older) style was already outdated when I started working with C (1994).

0
source

Source: https://habr.com/ru/post/910439/


All Articles