Skip to content Skip to main navigation Skip to footer

C Basic Syntax

You should already have a good understanding of the history of C, its strengths and basic structure of programs, so let’s talk about the basic syntax of the C language.

Table of Contents

 C Statement

A program in C consist of lines of statements that are commands for program execution, and C requires that statements must end with a semicolon, unless explicitly allowed without one.

int x = 1;

The above is a variable declaration statement that declares the integer variable x and sets its value to 1.

Multiple statements can be written in one line.

int x; x = 1;

The above example is written with two statements in one line. Therefore, line breaks between statements are not needed, just to make it easier to read the code.

A statement can also be written in multiple lines, which depends on a semicolon to determine on which line the statement ends.

int x;
x
=
1
;

In the above example, the second statement x = 1; is split into four lines. The compiler will automatically ignore line breaks inside the code.

A single semicolon is also a valid statement, called an “empty statement“, although it is useless.

;

C Expression

Various calculations in C are done mainly through expressions. An expression is a computational formula used to obtain a value.

1 + 2

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

An expression with a semicolon can also be a statement, but it has no practical effect.

8;
3 + 4;

The above example is two expressions that become statements when a semicolon is added.

Expressions differ from statements in two main ways:

  • Statements can contain expressions, but expressions themselves do not constitute statements.
  • Expressions have a return value, statements do not necessarily. Because statements are used to execute a command, many times they do not need a return value, for example, the variable declaration statement (int x = 1) does not have a return value.

 C Statement Block

C allows multiple statements to be formed into a block, also called a compound statement, using a pair of curly brackets {}. Syntactically, a block of statements can be considered as a compound statement consisting of multiple statements.

{
  int x;
  x = 1;
}

In the above example, the curly braces form a block of statements.

There is no need to add a semicolon at the end of the curly braces.

Whitespace in C

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

int x = 1;
// equal to
int x=1;

In the above example, the assignment symbol (=) can be preceded or followed by no spaces, because the compiler can distinguish syntactic units here without the help of spaces.

Multiple spaces between syntactic units are equivalent to one space.

int    x =     1;

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

Spaces are also used to indicate indentation. It makes no difference to the compiler whether multi-level code is indented or not; code without indentation is perfectly runnable. Indentation is emphasized only to improve the readability of the code and to make it easier to distinguish blocks of code.

Most C styles require that the next level of code be indented four spaces further than the previous level.

// Four spaces indent
if (x > 0)
    printf("positive\n");

// two spaces indent
if (x > 0)
  printf("positive\n");

Lines that contain only spaces are called blank lines, and the compiler will ignore the line entirely.

C Comments

Comments are descriptions of the code and are ignored by the compiler, i.e., they have no effect on the actual code.

There are two ways to represent comments in C. The first way is to place the comments between /*... */ between them, which allows for internal splitting.

/* comments */

You can insert such a comment into a line.

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

In the above example, /*filename*/ is used to specify the function argument, and the code that follows it will still be validly executed.

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

printf("a "); /* comments
printf("b ");
printf("c "); /* comments */
printf("d ");

The original intent of the above example was to have two comments at the end of the first and third lines of code. However, the first line comment forgets to write the end symbol, causing the first line comment to continue to the end of the third line.

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

// line comment
int x = 1; // another comment

Regardless of the type of comment, it should not be placed inside double quotes. A comment symbol inside double quotes will become part of the string, be interpreted as a normal symbol, and lose its comment role.

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

In the above example, the comment symbols inside the double quotes are treated as normal characters and have no comment role.

When compiled, the comment is replaced with a space, so min/* space */Value becomes min Value instead of minValue.

printf() in C

The printf() function will be used extensively in our examples, so here is a quick introduction to this function.

The role of printf() is to output the text of the argument to the screen. The f in its name stands for format (formatting), which means that the format of the output text can be customized.

printf("Hello World");

The above command will output the text “Hello World” on the screen.

printf() does not automatically add a line break at the end of the line, and when it finishes running, the cursor stays at the end of the output and does not automatically break the line. To move the cursor to the beginning of the next line, you can add a line break \n at the end of the output text.

printf("Hello World\n");

If there is a line break inside the text, this is also done by inserting a line break.

printf("Hello\nWorld\n");

The above example outputs a Hello first, then a line break, and then World at the beginning of the next line, followed by another line break.

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

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

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

#include <stdio.h>

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

In the above example, the function printf() can only be used if you add #include <stdio.h> to the source header.

C placeholder

printf() can specify a placeholder in the output text. A “placeholder” is a position that can be substituted with another value.

//output: There are 3 apples
printf("There are %i apples\n", 3);

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

The second argument to printf() is the value of the substitution placeholder, in the above example the integer 3 is replaced by %i. The output after execution is There are 3 apples.

In addition to %i, there is also %s, a commonly used placeholder to indicate that the substitution is for a string.

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

In the above example, %s means that a string is substituted, so the second argument to printf() must be a string, in this case Jane, and 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'clock has two placeholders, the first is the string placeholder %s and the second is the integer placeholder %i, corresponding to the second (Ben) and third (21) arguments of printf(), respectively. The output after execution is Ben says it is 21 o'clock.

The arguments to printf() are one-to-one with the placeholders. If there are n placeholders, printf() should have n+1 arguments. If the number of arguments is less than the corresponding placeholders, printf() can output any value in memory.

There are many types of placeholders for printf(), corresponding to the C language data types. The following is an alphabetical list of commonly used placeholders for easy reference, with the exact meaning described in a later section.

  • %a: hexadecimal floating point number, letters are output in lower case.
  • %A: hexadecimal floating point number, letters are output as uppercase.
  • %c: character.
  • %d: decimal integer.
  • %e: floating-point number using scientific notation, with lowercase e in the exponent part.
  • %E: floating-point number using scientific notation, with the E in the exponent part in upper case.
  • %i: integer, basically equivalent to %d.
  • %f: decimal number (contains both float type and double type).
  • %g: floating point number with 6 significant digits. Once the integer part exceeds 6 digits, it is automatically converted to scientific notation, and the e in the exponent part is lowercase.
  • %G: equivalent to %g, the only difference is that the E in the exponent part is uppercase.
  • %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: long double floating point number in scientific notation.
  • %Lf: long double floating point number.
  • %n: number of strings that have been output. The placeholder itself is not output, only the value is stored in the specified variable.
  • %o: octal integer.
  • %p: pointer.
  • %s: string.
  • %u: unsigned integer (unsigned int).
  • %x: hexadecimal integer.
  • %zd: size_t type.
  • %%: output a percent sign.

Output Format

printf() allows you to customize the output format of the placeholder.

1. Limited width

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

printf("%5d\n", 123); // output "  123"

In above example, %5d means that this placeholder is at least 5 bits wide. If it is less than 5 bits, a space will be added in front of the corresponding value.

The output value is right-aligned by default, i.e. the output content will be preceded by a space; if you wish to change to left-alignment and add a space after the output content, you can insert a - sign after the % of the placeholder.

printf("%-5d\n", 123); // output "123  "

In the above example, a space is added after the output 123.

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

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

In the above example, %12f means that the output floating point number should occupy at least 12 bits. Since the default display precision for decimals is 6 decimal places, 2 spaces will be added to the header of the 123.45 output.

2. Limited decimal places

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

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

In the above example, if you want the decimal point to be followed by 3 bits (0.500), the placeholder should be written as %.3f.

This writing style can be used in combination with the qualified width placeholder.

// Output: "  0.50"
printf("%6.2f\n", 0.5);

In the above example, %6.2f means that the minimum width of the output string is 6 and the number of decimal places is 2. Therefore, there are two spaces at the head of the output string.

3.Output partial string

The %s placeholder is used to output the string, and the default is to output it all. If you want to output only the beginning part, you can use %. [m]s specifies the length of the output, where [m] represents a number indicating the length of the desired output.

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

In the above example, the placeholder %.5s means that only the first 5 characters of the string “hello world” are output, i.e. “hello“.

Standard libraries, header files

The program needs to use functions that you don’t necessarily need to write yourself, the C language may already come with it. The programmer can just call these functions and save himself from writing code. For example, printf() is a function that comes with the C language and can be called to output content on the screen.

All these functions that come with the C language are collectively called the “standard library” because they are written in a standard way, and what functions are included and how they should be used are specified so that the code can be standardized and portable.

Different functions are defined in different files, which are collectively called “header files“. If the system comes with a function, it must also come with a header file describing that function, for example, the header file for printf() is the system’s own stdio.h. The header file is usually suffixed with .h.

If you want to use a function, you must first load the corresponding header file, which is done using the #include command. This is why stdio.h must be loaded before you can use printf().

#include <stdio.h>

Note: The #include statement to load a header file does not need to end with a semicolon.

Was This Article Helpful?

2
Related Articles
0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.