C Language Basic Grammar - Chapter 1

C language basic syntax

statement

The code of C language consists of a line of statements (statements). A statement is an operation command executed by a program. The C language stipulates that a statement must end with a semicolon, unless it is clearly stipulated that the semicolon can not be written.

int x = 1;

The above is a variable declaration statement, which declares an integer variable xand sets the value to it 1.

Multiple statements can be written on one line.

int x; x = 1;

The above example is two statements written on one line. Therefore, the line breaks between statements are not necessary, but are just for the convenience of reading the code.

A statement can also be written in multiple lines. In this case, it is necessary to rely on the semicolon to determine which line the statement ends on.

int x;
x
=
1
;

In the example above, the second statement x = 1;is broken into four lines. The compiler will automatically ignore newlines in the code.

A single semicolon is also a valid statement, called an "empty statement", although it has no effect.

;

expression

Various calculations in C language are mainly done through expressions. An expression is a calculation that is used to obtain a value.

1 + 2

The above code is an expression used to obtain 1 + 2the result of this arithmetic calculation.

An expression plus a semicolon can also become a statement, but it has no practical effect.

8;
3 + 4;

The above example is two expressions, and after adding a semicolon, it becomes a statement.

Expressions differ from statements in two main ways:

  • Statements can contain expressions, but expressions themselves do not constitute statements.
  • Expressions have return values, statements do not necessarily have. Because the statement is used to execute a certain command, it does not need to return a value in many cases. For example, the variable declaration statement ( int x = 1) has no return value.

statement block

The C language allows multiple statements to use a pair of curly braces {}to form a block, also known as a compound statement (compounded statement). Syntactically, a statement block can be regarded as a compound statement composed of multiple statements.

{
    
    
  int x;
  x = 1;
}

In the example above, curly braces form a statement block.

A semicolon does not need to be added at the end of the curly braces.

space

Spaces in the C language are mainly used to help the compiler distinguish grammatical units. If the syntactic units can be distinguished without spaces, the spaces are not necessary, but only to increase the readability of the code.

int x = 1;
// 等同于
int x=1;

In the above example, it doesn’t matter whether there are spaces before and after the assignment sign ( =), because the compiler can distinguish the grammatical units without using spaces.

Multiple spaces between syntactic units are equivalent to a single space.

int    x =     1;

In the above example, multiple spaces between each grammatical unit have the same effect as a single space.

Spaces are also used to indicate indentation. Whether the multi-level code is indented or not does not make any difference to the compiler, and the code without indentation is also fully executable. The emphasis on code indentation is only to enhance the readability of the code and facilitate the distinction of code blocks.

The style requirement for most C languages ​​is that the next level of code is indented 4 spaces beyond the previous level. In order to write compactly, this book uses the abbreviation of two spaces.

// 缩进四个空格
if (x > 0)
    printf("positive\n");

// 缩进两个空格
if (x > 0)
  printf("positive\n");

A line containing only whitespace is called a blank line and is completely ignored by the compiler.

note

An annotation is a description of the code, and the compiler ignores the annotation, that is, the annotation has no effect on the actual code.

Comments in C language can be expressed in two ways. The first way is to put comments in /*...*/between, which can be divided into lines.

/* 注释 */

/*
  这是一行注释
*/

Such comments can be inserted inline.

int open(char* s /* file name */, int mode);

In the above example, /* file name */it is used to explain the function parameters, and the code following it will still be executed effectively.

This kind of comment must not forget to write the end symbol */, otherwise it will easily lead to errors.

printf("a "); /* 注释一
printf("b ");
printf("c "); /* 注释二 */
printf("d ");

The original meaning of the above example is that there are two comments at the end of the first and third lines of code. However, the first line of comment forgot to write the end symbol, causing the comment to continue to the end of the third line.

The second way of writing is to put the comment //after the double slash, from the double slash to the end of the line is a comment. This kind of comment can only be a single line, and can be placed at the beginning of the line or at the end of a line of statement. This is a new syntax added to the C99 standard.

// 这是一行注释

int x = 1; // 这也是注释

No matter what kind of comment it is, it cannot be placed in double quotes. The comment symbols inside the double quotes will become part of the string, interpreted as ordinary symbols, and lose their comment function.

printf("// hello /* world */ ");

In the above example, the comment symbols inside the double quotes will be regarded as ordinary characters and have no comment function.

When compiling, comments are replaced with a single space, so min/* space */Valuewould become min Value, instead of minValue.

printf()

basic usage

The examples in this book will use printf()functions extensively, so let's introduce this function first.

printf()The effect of is to output the parameter text to the screen. fThe representative format(formatting) in its name means that the format of the output text can be customized.

printf("Hello World");

The above command will output a line of text "Hello World" on the screen.

printf()A newline character will not be automatically added at the end of the line. After the operation ends, the cursor will stay at the end of the output, and no newline will be automatically added. To move the cursor to the beginning of the next line, add a newline at the end of the output text \n.

printf("Hello World\n");

If there is a line break inside the text, it is also achieved by inserting a line break.

printf("Hello\nWorld\n");

The above example first outputs one Hello, then a newline, and outputs at the beginning of the next line World, and then another newline.

The above example can also be written as two printf(), the effect is exactly the same.

printf("Hello\n");
printf("World\n");

printf()stdio.hIt is defined in the header file of the standard library . Before using this function, this header file must be introduced at the head of the source code file.

#include <stdio.h>

int main(void) {
    
    
  printf("Hello World\n");
}

In the above example, this function #include <stdio.h>can only be used if it is added at the source port printf(). #includeFor a detailed explanation of the directive, see the chapter "Preprocessor".

Placeholder

printf()Placeholders can be specified in the output text. The so-called "placeholder" means that this position can be substituted with other values.

// 输出 There are 3 apples
printf("There are %i apples\n", 3);

In the above example, There are %i apples\nit is the output text, which %iis a placeholder, indicating that this position should be replaced with other values. The first character of the placeholder is always a percent sign %, and the second character indicates the type of the placeholder, %iindicating that the value substituted here must be an integer.

printf()The second parameter of is the value of the replacement placeholder, the above example is an integer 3replacement %i. The output after execution is There are 3 apples.

In addition to the commonly used placeholders %i, there %sare also strings that represent substitutions.

printf("%s will come tonight\n", "Jane");

In the above example, %sit means that a string is substituted, so printf()the second parameter must be a string, as in this example Jane. The output after execution is Jane will come tonight.

Multiple placeholders can be used in the output text.

printf("%s says it is %i o'clock\n", "Ben", 21);

In the above example, the output text %s says it is %i o'clockhas two placeholders, the first is a string placeholder %s, the second is an integer placeholder %i, corresponding printf()to the second parameter ( Ben) and the third parameter ( 21) respectively. The output after execution is Ben says it is 21 o'clock.

printf()There is a one-to-one correspondence between parameters and placeholders. If there is na placeholder, printf()there should be n + 1one for the parameter. If the number of arguments is less than the corresponding placeholders, printf()arbitrary values ​​in memory may be output.

printf()There are many kinds of placeholders corresponding to the data types of C language. The commonly used placeholders are listed below in alphabetical order for easy search, and the specific meanings are introduced in later chapters.

  • %a: Hexadecimal floating point number, the letter output is lowercase.
  • %A: Hexadecimal floating-point number, the letter output is uppercase.
  • %c:character.
  • %d: Decimal integer.
  • %e: A floating-point number that uses scientific notation, and the exponent part eis lowercase.
  • %E: A floating-point number that uses scientific notation, and the exponent part Eis capitalized.
  • %i: Integer, basically equivalent to %d.
  • %f: Decimal (contains floattype and doubletype).
  • %g: Floating point number with 6 significant figures. Once the integer part exceeds 6 digits, it will be automatically converted to scientific notation, and the exponent part will ebe lowercase.
  • %G: Equivalent %g, the only difference is Ethat the exponent is capitalized.
  • %hd: Decimal short int type.
  • %ho: Octal short int type.
  • %hx: Hexadecimal short int type.
  • %hu: unsigned short int type.
  • %ld: Decimal long int type.
  • %lo: Octal long int type.
  • %lx: hexadecimal long int type.
  • %lu: unsigned long int type.
  • %lld: Decimal long long int type.
  • %llo: Octal long long int type.
  • %llx: hexadecimal long long int type.
  • %llu: unsigned long long int type.
  • %Le: A long double floating-point number expressed in scientific notation.
  • %Lf: Long double type floating point number.
  • %n: The number of strings that have been output. The placeholder does not output itself, but only stores the value in the specified variable.
  • %o: Octal integer.
  • %p:pointer.
  • %s: String.
  • %u: unsigned integer (unsigned int).
  • %x: Hexadecimal integer.
  • %zd: size_ttype.
  • %%: Output a percent sign.

output format

printf()The output format of the placeholders can be customized.

(1) Limited width

printf()Allows to limit the minimum width of the placeholder.

printf("%5d\n", 123); // 输出为 "  123"

In the above example, %5dit means that the width of this placeholder is at least 5 bits. If there are less than 5 digits, a space will be added in front of the corresponding value.

The output value is right-aligned by default, that is, there will be a space in front of the output content; if you want to change it to left-aligned, add a space after the output content, and you can %insert a -number after the placeholder.

printf("%-5d\n", 123); // 输出为 "123  "

In the above example, 123spaces are added after the output.

For decimals, this qualifier limits the minimum display width of all numbers.

// 输出 "  123.450000"
printf("%12f\n", 123.45);

In the above example, %12fthe output floating-point number must occupy at least 12 bits. Since the default display precision of the decimal is 6 digits after the decimal point, 123.452 spaces will be added to the head of the output result.

(2) Always display the plus and minus signs

By default, numbers printf()are not displayed for positive numbers +, only for negative -numbers. If you want positive numbers to be output as well , you can add one after +the placeholder .%+

printf("%+d\n", 12); // 输出 +12
printf("%+d\n", -12); // 输出 -12

In the above example, %+dyou can ensure that the output value always has a sign.

(3) Limit the number of decimal places

When outputting decimals, it is sometimes desirable to limit the number of decimal places. For example, if you want to keep only two digits after the decimal point, the placeholder can be written as %.2f.

// 输出 Number is 0.50
printf("Number is %.2f\n", 0.5);

In the above example, if you want to output 3 digits ( 0.500) after the decimal point, the placeholder should be written as %.3f.

This way of writing can be used in combination with limited-width placeholders.

// 输出为 "  0.50"
printf("%6.2f\n", 0.5);

In the above example, %6.2fit means that the minimum width of the output string is 6, and the number of decimal places is 2. So, the output string has two spaces at the head.

Both the minimum width and the number of decimal places can be *replaced by printf()the parameters passed in.

printf("%*.*f\n", 6, 2, 0.5);

// 等同于
printf("%6.2f\n", 0.5);

In the example above, %*.*fthe two asterisks pass printf()the two parameters 6and 2pass in.

(4) output part of the string

%sPlaceholders are used to output strings, and the default is all output. If you only want to output the beginning part, you can %.[m]sspecify the length of the output, which [m]represents a number, indicating the length of the output.

// 输出 hello
printf("%.5s\n", "hello world");

In the above example, the placeholder %.5sindicates that only the first 5 characters of the string "hello world" are output, that is, "hello".

standard library, header files

The functions needed by the program do not necessarily need to be written by yourself, and the C language may already come with it. Programmers only need to call these built-in functions, saving themselves from writing code. For example, printf()this function comes with the C language, as long as you call it, you can output the content on the screen.

All these functions that come with the C language are collectively referred to as the "standard library" (standard library), because they are written into the standard. What functions are included and how they should be used are all stipulated, so as to ensure the specification of the code and portable.

Different functions are defined in different files, and these files are collectively called "header files". If the system comes with a certain function, it must also come with a header file describing this function, for example, the printf()header file is the system's own stdio.h. The suffix for header files is usually .h.

If you want to use a certain function, you must first load the corresponding header file, and the loading uses #includethe command. This is why printf()it must be loaded before use stdio.h.

#include <stdio.h>

Note that the statement that loads the header file #includedoes not need to end with a semicolon, see the chapter "Preprocessor" for details.

Guess you like

Origin blog.csdn.net/ALiLiLiYa/article/details/132128600