Skip to content

section3_syntax

Marantess edited this page Jan 11, 2019 · 2 revisions

C - Basic Syntax

Tokens in C

A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens:

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

The individual tokens are:

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

Semicolons

When dealing with a C program, the semicolon is a statement terminator, i.e., each individual statement must be ended with a semicolon. It indicates the end of one logical entity.

Comments

Comments aren't actually code. In fact, they are ignored by the compiler. But they are very useful to remind you what the program/statement does.

You can insert a comment by using //. With this comment syntax you can only comment a single line. I.e., the text after // is ignored only on that line.

// This is a one line commment

Another way to make comments is using /* */. Anything between /* */ is treated as a comment. This comment syntax allows you to use multiple lines. The comment starts at /* and all the text after it will be ignored until the */ is found.

/*
This is a
multi line
comment
*/

Comments can be a very useful way of explaining what’s going on in the program.

Identifiers

A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits (0 to 9).

C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C.

Keywords

A keyword is a reserved language word with a special meaning. You already seen some keywords: int, return and void.

Because keywords have a special meaning for the language, you can't redefine them or use them to name variables, for example.

Here is a list of C keywords.

Whitespace in C

A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it.

Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −

int height;

there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −

fruit = apples + oranges;   // get the total fruit

no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish to increase readability.