Skip to content

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

../res/Pasted image 20240206171153.png

Compile

$ gcc prog.c

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

$ gcc prog.c -o [filename]

Using library functions: Tell the compiler the library you use

When adding

#include <math.h>

We should use

$ gcc prog.c -o prog -lm
  • -l: Use library
  • m: Math library

If Not Using -lm

Structure of a C Program

/* comment line 1
   comment line 2
*/

preprocessor instructions

int main()
{
    statements;
    return 0;
}
/* 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() or int main()
    • enrty
  • body
    • enclosed by {}
    • statements
    • return 0: last

Function

Declaration

float square(float x)

Implementation

float square(float x)
{
    return x*x;
}

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

int a;
float b;

Assignment

a=10;
b = 15.6;

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