01. C programming language
As seen before C programming language is:
- low-level (calculational model is equal to hardware);
- procedural algorithmic (has classical control flow, data types, variables, function calls etc.)
C program structure
All code is formed by functions
Function is subroutine with a number of arguments (incl. none) and return value (can be void)
A program must contain main() function
main() is called from outside (so called «C runtime»), and returned an int value back to C runtime
main() accepts two arguments (integer and array of strings, see later); in many systems they corresponds program command line arguments
All data is described by variables.
Variable is labeled peace of memory corresponding data of certain type; the amount of memory variable has consumed is always fixed and corresponds its type
- Variables must be provisionally defined
- Variable can be:
global:
defined (almost always) between functions,
- placed statically in data memory segment,
- accessible (visible by name) from any part of the program,
- exists all along the program runs;
local:
defined inside a function,
- placed dynamically in stack,
- accessible only from the function interior,
- lose it's value when function function call is finished;
register:
defined inside a function,
- placed dynamically in CPU registers when applicable, otherwise in stack
- accessible only from the function interior,
- lose it's value when function function call is finished;
- Data type can be:
- Scalar: integers of various size/signness and floats with various size
Pointer: address of certain type data or function; all pointers have one size
- Structure: a fixed number of data pieces of several types, in a declared order, treated as one memory chunk
- Function control flow contents:
- Expressions
- Conditionals
- Circles
- Switches
- Returns
- All code is transformed by preprocessor
- To include other source files (mainly macros and library declarations)
To expand macros
- C preprocessor
- has parametric macros
- has preprocessor-time conditionals
- has preprocessor-time expressions
C program example
1 #include <stdio.h>
2 #define START 100500
3
4 int num=START;
5 float flt=2.718281828459045;
6
7 int main(int argc, char *argv[]) {
8 int i;
9 register int j;
10
11 printf("Enter a cardinal: ");
12 scanf("%d", &num);
13
14 flt = 0.0;
15 for(i=1; i<num; i++)
16 for(j=1; j<i; j++)
17 flt += 1./j;
18
19 printf("Result is %f\n", flt);
20 return 0;
21 }