C Program Structure
略去大部分关于背景知识的介绍
Why C/C++
- Advantages:
- Powerful, flexible, efficient, portable
- A high-level language with low-level operations
- Closely related with UNIX / Linux
- Influence on other languages: C#, Java
- Disadvantages:
- Using pointers might be confusing and cause errors
- Requires attention to low-level details
- More difficult to learn, especially for C++
C Programs
.c
- Sentence separated by
;
ASCII
In hello.c
characters are saved by numbers (ASCII codes)
ASCII TABLE
Program Storage
Program store in - Hard disk: Binary file (compiled); instructions; data - System Memory: when loaded
Size measure
bit -> Byte -> KB -> MB -> TB
Encoding
- Bit: 0 / 1
- Byte: 8bit (\(2^8\))
Compilation of a program
Compile
If your program has no error, the compiler will call the linker automatically to do the linking and produce the executable file named a.out.
Assume output file
Using library functions: Tell the compiler the library you use
When adding
We should use
-l
: Use librarym
: Math library
If Not Using -lm
Structure of a C Program
/* a program to print Hello World! */
#include <stdio.h> /* preprocessor instruction */
int main() /* header */
{ /* begin body */
/* print message statement */
printf(“hello, world!\n”);
return 0;
} /* end body */
- Preprocessor instructions
- instructions to the preprocessor of the compiler
- start with
#
- Eg.
#include <filename>
#define <CONSTANT_NAME> <value>
main()
orint main()
- enrty
- body
- enclosed by
{}
- statements
return 0
: last
- enclosed by
Function
Declaration
Implementation
Variable
Nothing but a name given to a storage area that our programs can manipulate
Variable type: determines the size and layout of the variable's memory
\[
\begin{array}{|ll|}
\hline
\text { char: } & 1 \text { byte } \\
\text { int: } & 4 \text { bytes } \\
\text { long: } & 8 \text { bytes } \\
\text { float: } & 4 \text { bytes } \\
\text { double: } & 8 \text { bytes } \\
\hline
\end{array}
\]
Declaration
Assignment
Develop with IDE
VSCode / Dev-C++
Standard library
- The standard library for the C programming language
- Provides macros, type definitions and functions
- Mathematical computations
- Input/output processing
- Memory management
- Several other operating system services