C Syntax
Basic Structure of a C Program
A C program follows a consistent structure. The compiler expects specific elements in order: preprocessing directives, functions, and statements.
At minimum, a program must include the `main()` function, which is the entry point. Inside `main()`, we place instructions that define the program's behavior.
#include <stdio.h>
int main(void) {
printf("Hello, C!\n");
return 0;
}
Hello, C!
C Program Components
**Preprocessor Directives**: Lines beginning with `#`, such as `#include`, are processed before compilation.
**Functions**: Named blocks of code that perform tasks. Every program needs `main()`, while additional functions are optional.
**Statements and Expressions**: Instructions inside functions, typically ending with a semicolon.
**Comments**: Non-executable notes in code. Use `//` for single-line and `/* ... */` for multi-line comments.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main(void) {
int result = add(3, 4);
printf("%d\n", result);
return 0;
}
7
Identifiers, Keywords, and Formatting
Identifiers are names given to variables, functions, and other elements. They must begin with a letter or underscore, may contain digits and underscores thereafter, and cannot be keywords. C identifiers are case-sensitive.
Keywords are reserved words in C, such as `int`, `return`, `while`, and `if`. These cannot be used as identifiers.
Consistent formatting—using indentation, spacing, and braces—improves readability but does not change program execution.
Category | Examples |
---|---|
Valid identifiers | x, total_sum, _count |
Invalid identifiers | 2ndValue, float (keyword) |
Keywords | int, char, if, else, return |
Escape Sequences in Strings
C supports escape sequences within strings, starting with a backslash (`\`).
These sequences allow inclusion of special characters such as newlines, tabs, or quotation marks.
#include <stdio.h>
int main(void) {
printf("Hello World\tC\n");
return 0;
}
Hello World C
Escape Sequence | Meaning |
---|---|
\\n | New line |
\\t | Tab space |
\\\\ | Backslash |
\\" | Double quote |