The grammar style of C language and Code Writing specification guide _c language

Source: Internet
Author: User
Tags constant function definition function prototype goto

C Code:

#include <stdio.h>
int main (void)
{
 printf ("That's right style\n");
 return 0;
}

In a standard C language program, the most special one is the main function, and in the final analysis it is a function only because it has a special status of the first executive power, in other words, because a person is a governor it is not human? So the function should have it all, so what else does the function have?

Functions are generally divided into inline functions (C99) (inline functions are not C + + exclusive, C language also has, specifically see the front link and non-inline ordinary functions, they have a very obvious characteristic (in general), that is not to write the prototype directly above the main function definition, even without the ' inline ' keyword , the compiler defaults to an inline function, but some of the concurrency problems that follow are not considered by the compiler.

Normal functions The correct form should be for declaration and definition separation, the declaration is a function prototype, the function prototype should have a function name, a parameter list, a return value type and a semicolon. The definition is the inner of the function, and within the curly braces is the definition of the function:

//...
int function (int arg_1, float arg_2);
//...
int main (int argc, char* argv[])
{
 int output = function (one, 22.0);
 printf ("%d\n", output);
 return 0;
}

int function (int arg_1, float arg_2)
{
 int return_value = arg_1;
 float temp_float = arg_2;
 return return_value;
} 


As mentioned above, it is a good habit and norm to write your function in the beginning (before the main function) and write your function definition at the end (after the main function) when it is not necessary. The so-called code neat way, is so.

Another classification of functions is that there is a return value and no return value, the type of the return value can be either built-in (build-in) or defined by itself (struct, union, etc.), and no return value is void.

Why do we condemn void main ()? Because this is completely Chinese-style education extended out of the tan style, the return value of the main function seems useless, is actually received by the operating system, under the Windows operating system may not be very "serious" (actually there), When you use Linux, you will clearly find a C language program's main return value is related to a system can be normal, efficient operation, here a little bit, 0 in the Linux program pipeline communication between the meaning of the error. So please throw away the void main.
Why do we have a criticism of the notation of the omitted return value of main ()? The person who can invent this kind of writing, must understand, in C language, if a function does not explicitly declare its own return value, it is considered to be int by default, but this step is controlled by the compiler, however, the C language design is to let us grasp everything possible, and all the uncertainties we should not let it exist. Second, there is a principle that can do it yourself do not let the compiler do.

Why are we dissatisfied with the argument being left vacant (int main ())? In C, the list of parameters for a function has three legal forms:

 int function ();
 int function (void);
 int function (int arg_n);
 int function (int arg_n, ...);

The first represents an unknown parameter, and the second represents no parameters, the third represents a parameter, the fourth represents an unknown parameter, and the first parameter type is int, and the unknown parameter has a solution in the C language, which is a variable-length parameter list, referring to the C standard library, where we explain the basis We have to keep everything in our hands, we don't fill in the parentheses in the parameters, represents what we think the beginning means is that it's empty, so we should make it clear that it's void, and not let it be a function of unknown parameter lengths, so that the compiler cannot detect errors when you accidentally pass in the arguments.

int main (int argc, char* argv[]) and int main (void) are the C-language standard forms we should write
For indentation, in addition to the symbolic indentation provided by the compiler, we can give ourselves a specification (please use little or no tab), for example, each piece of code teaches a block of code with a 4-lattice indent.
For learning C, use the. c file and the C language compiler to practice and write C programs, please do not use C + + files to write C language programs, and to justify the use of C + + features for efficiency in the C language, we are the next generation of the motherland, is the future of the motherland, please do not let yourself destroy in the present, cherish programming , away from Tsinghua University Press.

This is not because of emotion, but really, the following code:

 /*file:test.c*/
 #include <stdio.h>
 #define SIZES 5
 int main (void)
 {
  int* c_pointer = malloc (Sizes * sizeof (int));
  * * Something has happened
  /free (c_pointer);
  return 0;
 }

This is a standard C language program, but it can be compiled in C + + compiler run it? In other words, when you change the file name extension from. C to. cpp, does it compile? The answer is no.

Why? The answer is that C + + does not support void* implicit conversions to other types of pointers, but the C language allows. There are a lot of C in a different place, perhaps some people say C + + is a superset of the, but I do not think so, a language is the emergence of its significance, the key is how we play its greatest advantage, rather than by confusing concepts to enhance practicality.

The writing of the program formula

A person living in the world, always pay attention to their own behavior, and writing procedures are so, for a normative to allow others to understand the procedures, we should minimize obstacles, such as:

 int main (void)
 {int complex_int=100;
 int i,j,k,x;
 for (int temp=0;temp<complex_int;++temp) {k=temp;
 X=k+complex_int;}
 printf (complex_int= "%d is k=%d x=%d\n", complex_int,k,x);
 return 0;}

For the above code, I always appear in the class of my classmates, but this piece of code in addition to let others confused, oneself in debugging time is also very inconvenient, often encountered problems, even if the IDE prompted a mistake somewhere, you can not find the problem, often someone to ask me where the wrong, most of the situation is less a semicolon, parentheses, or scope over, why?

If you start to write the code clearly, this situation is very rare, it is difficult to meet. For a code, we should pay attention to making it clear.

Use spaces on both sides of the equals sign:

 int complex_int = 100;

Use a declaration definition for multiple variables, or a function declaration definition, when a function is used, note that the variable is separated by a space:

 int I, j, K, x;//but it's very not advisable to declare a variable that is difficult to understand.
 printf ("Complex_int =%d is k =%d x =%d\n", Complex_int, K, x);
 void present (int arg_1, double arg_2);

For a clear program, we have to make each step clear and meaningful, which requires that we try to make the code look structured or holistic as we write the program. Try to make each program a row, if there is a special need for multiple formulas to write on the same line, you can use, operators to combine, but it will make the program more difficult to understand, and later debugging more difficult to find errors.

 /*style 1*/for 
 (int temp = 0;temp < Complex_int;++temp)
 {
  k = temp;
  x = k + complex_int;
 }
 /*style 2*/for
 (int temp = 0;temp < Complex_int;++temp) {
  k = temp;
  x = k + complex_int;
 }

For the above code, is the C language code curly braces of the two styles, it is best to choose one of them as their own programming style, so that your program will look clearer, the pros and cons of mixing is not to say, the key is to look at personal style.

For a scope, there is a frequently used exception in the C language, when a conditional statement, or loop has only one statement, we often omit the curly braces {}, but only use a semicolon as the end, which in many cases makes the code no longer verbose:

 if (Pointo_int = = NULL)
  fprintf (stderr, "The pointer is null!\n");
 else
 {
  printf ("%d\n", *pointo_int);
  Pointo_int = pointo_int->next;
 }

In this code, the code below the IF statement is not indicated by the {} operator, but, according to the syntax, the statement does fall within the scope of the IF statement, and if we write {} at this point the code will look too verbose. But sometimes, this feature is not so interesting, when using nested features, it is recommended to use {} for explicit scoping, rather than using the default scope:

 for (int i = 0;i< 10;++i) for
  (int k = 0;k < 10;++k) while
   (flag!= 1)
    Set_value (arr[i][k));

This code, it looks very concise, but it is a big problem, when we want to debug this piece of code, always need to modify its construction, and this brings potential pitfalls. Therefore, it is recommended that you can use {} for packing whenever you use nested nesting.

To sum up, when you start to write a standard C language program, please write down these things:

 #include <stdio.h>

 int main (void)
 {return
  0;
 }


C Code Specification

Named

As long as you mention code specifications, you have to say a problem.
In some small demo programs, it may be a silly idea to think of a name, but as long as the program goes up to the level where you need to design, think, and review, you need to consider naming the problem.
Function Name:

C, we can let the underline or the words help us to express the function function:

Prefix:

    • Set can represent setting a parameter to a value
    • Get can represent the value of getting a parameter
    • Is can indicate whether this is the case

Suffix:

    • Max/min can represent the maximum (small) number of operations
    • CNT can represent the current number of operations
    • Key some sort of critical value
   size_t get_counts ();
   size_t Retry_max ();
   int Is_empty ();

The only thing to note is not to let the naming go too far, simply to keep the action and the purpose, and the detailed functionality can be explained further by the document.
Structure Name:

Because the label of the structure does not pollute the name, that is, the label is not within the named search range, so you can use it safely:

Some people used to use TypeDef, and some people like to use struct tag obj, the latter is more, but the former is also a good way, the beholder.

  /* Method 1*/
  struct inetaddr_4{
    int port;
    char * name;
  struct Inetaddr_4 *addr_info;
  /* Method 2*/
  typedef struct _addr{
    int port;
    char * name;
  } Inetaddr_4;
  


There is also no compilation error in the same file.
variable naming

    • All characters Use lowercase
    • More meaning can be used _ to assist
    • Align to = for standard
    • Type, and the variable name is left-aligned.

Equal to the left and right ends, with at least one space.

  int main (void)
  {
   int   counts = 0;
   Inetaddr_4 *addr = NULL;

   return 0;
  }

In order to prevent errors when the pointer declaration is defined, it is always not an error to cling to the variable name.

  Inetaddr_4 *addr, object, *addr_2;

Where addr and addr_2 are pointers, and object is a complete object on a stack, not a pointer.

Global variables can be used sparingly, you must use the case, you can consider adding a prefix g_

  int g_counts;

#define Naming

    • All characters are capitalized and split with _.
    • If more than one statement, use do{...} while (0) carries on the parcel, prevents; Error.
  #define SWAP (x, y)  \
  do{      \
   x = x + y;  \
   y = x-y;   \
   x = XY;   \
  }while (0)

Of course, this Exchange macro is actually a little defective and will be raised in the rear. Here is the code specification, which is not repeated.

Enum naming

    • All characters are capitalized and separated by _
    • As opposed to define, an enum applies to a constant declaration of the same type, rather than a single independent constant. Often appear in groups.

Formatting code

Curly braces {}

    • Mixed use is in line with frugal thinking, but there is a slight structural disorder.
    • A single use can better make the code structure clearer.
    • The so-called mixing, single refers to whether or not always use {} for code wrapping.
    • Some people think that when a single statement is not necessary to add {}, others are accustomed to add
    • When the scope is more than one screen, you can use annotations to indicate the {} scope

while (1) {
   if (tmp = = NULL) {break
    ;
   }
   else if (Fanny = 1) {
    ... Probably more than one screen of code
   }/*else if fanny*/
  }/*end while*/

If you have less code, but more nesting, you can use this method to annotate.

Brackets ()

It is suggested that, in addition to the function call, use () in a similar case, such as a conditional statement, to empty a space after the keyword, and then to the () statement, my personal habit is not blank, but there is always such a statement.

  if (space = = NULL) {
   /**todo**/
  } while
  (1) {
   /** I am accustomed to writing so **/
  }
  strcpy (str1, str2);/** The first method is to differentiate **/return 0 from the writing of function calls
  ;
Switch

Be sure to put a default in the end, even though it will never be used.
If you need to use a new variable for each case, you can wrap it up with {} and do all of the things inside.

  Switch (...)
  {Case
   1:
    /**todo**/break
    ;

   Case 2:
   {
    int new_vari;
    /** Create a new variable with {} wrapped up **/
   } break
   ;

   Default:
    call_error ();
  }

Goto

Although many people, many books are reminded not to use the GOTO keyword, but use setjmp and longjmp to replace it, but this is still the words, the beholder, if Goto can make the code clear, then why not, this point of view is also recently realized (not my own words).
The official documents can be queried for specific use.
Statement

    • You should make the complete statement appear only once in each row.
    • This is also true for variable declaration definitions
    • The reason for this is that it makes the document more specific.

Header File Protection

In the case of a header file, it is possible to include (#include) multiple times in a program, and a compilation error occurs if the header File protection is missing
Do not use _ as the beginning or end of a macro.

  #ifndef vector_h_include
   #define Vector_h_include
    /**todo**/
   #endif 

Macro

C language macros have many drawbacks, so try to use the inline function instead of macros. There will be an explanation in the rear.
However, please do not discard macros, such as a new macro in C11.
variable

The first time all declared variables are initialized, because there is no harm in doing so, and can reduce the likelihood of errors.
function

The function should be as short as possible, an ANSI screen for the best.
If a loop has an empty statement, use {} to mount it to avoid an unexpected occurrence.

 while (*is_end++!= ' ")
 {
  ;
 }

Although it is an empty loop body, it is written so as not to cause a false loop.

Try not to let the function return value directly as a conditional statement, which can greatly reduce readability

 if (is_eof (file) = = 0) is
  better than
 if (!is_eof (file))

Instead of giving up readability for convenience or a little bit of the so-called speed rise (maybe not at all), use embedded assignment statements

 int add = ten;
 int num = one;
 int thr =;
 Add = add + thr;
 num = add + 20;

Don't write

 num = (add = add + thr) + 20;

Floating point numbers

    • Always remember not to use floating-point numbers to compare whether they are equal or unequal.
    • If you use floating-point numbers on discrete data, like a loop counter, then ...

Other

Use #if rather than #ifdef
You can use define () to replace the #ifdef的功能

 #if!define (users_define)
  #define Users_define ...
 #endif

For certain large segments of code that need to be eliminated, we cannot use annotation/**/because annotations cannot be embedded with annotations (//except), we can use black Magic:

 #if not_declaration
  /** want to annotate the code **/
 #endif

Do not use pure numbers
means not using unmarked numbers, because you probably don't know what that number means when you look at the source code for months.
Instead, use #define to give it a name to illustrate the meaning of this number.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.