08. C programming language at a glance
Expressions
- all of it
@= where "@" is operation
post and per ++ and --
a=b=c (i. e. a=(b=c))
- a = b, c (i. e. a=b and c i calculated)
what does: a = n, c = d
Types
See previous lecture
+:
void — not a type but
void function(…) indicates no return value is expected
void *pointer indicates «universal» pointer (address) type that can contain any pointer without a cast, but has no address arithmetic nor can be dereferenced
static modifier
- on globals — not goes to global symbol talbe
- on locals — statically placed on memory instead of stack (⇒ keeped between calls):
- …
Functions
See previous lecture
+:
we can always skip return value (esp. int)
arguments are passed only by value
Arrays, functions and other names are in fact pointers
If you want to change a variable, pass pointer to this variable
- Thus «pointer to pointer» and other such stuff:
1 #include <stdio.h> 2 3 4 int A[10] = {1,2,3,4,5,6,7,8,9,0}; 5 6 void findcell(int **p, int *arr, int len, int value) { 7 int i; 8 *p = NULL; 9 for(i=0; i<len; i++) 10 if(arr[i] == value) 11 *p = &arr[i]; /* = arr+i */ 12 } 13 14 15 int main(int argc, char *argv[]) { 16 int *p; 17 findcell(&p, A, 10, 7); 18 printf("%d==%d\n", *p, A[6]); 19 *p = 100500; 20 printf("%d==%d\n", *p, A[6]); 21 return 0; 22 }
- …
Control flow
operator grouping by {}
if()
while() {} and do {} while();
for(;;)
not a «cycle with counter»
- 4-point canonical cycle scheme
switch()
may be or may be not a sequence of if-s (e. g. arithmetic goto)
H/W
EJudge: HelloWorld 'Hello world'
Write a simple program that prints "Hello, World!"
Hello, World!
EJudge: DummyCalc 'Dummy calculator'
Write a program that reads expressions by "%d%c%d" pattern (first and third arguments are integers and second is operation) and prints the result of operation. Operations are '+', '-', '*', '/' and '^' (integer power). If operation is unknown, program should print (to stdout, not to stderr) an "Unknown operation" message. If input doesn't correspond the pattern (e. g. "END" is given instead of expression), the program stops. Zero division shall be equal to 0 and negative power shall be equal to 1 (NB: $$-1^-1=1$$ also!)
3+3 100*7 12^3 42/0 100500!500100 2^12 100/3 -1^-1 25-50 .
6 700 1728 0 Unknown operation 4096 33 1 -25
EJudge: ShuffleArray 'Shuffle an array'
Write a program, that reads a cardinal N — an array size, then N integers. Reorder the array in such a way that the elements of it's first half take corresponded even positions, and the elements of it's second half reordered backwards and take odd positions. If N is odd, first half is bigger than second.
11 23 89 34 35 79 26 78 72 37 86 82
23 82 89 86 34 37 35 72 79 78 26