C Lecture 3
[Previous Lecture]
[Lecture Index]
[Next Lecture]
Compiling Programs
To compile and link a C program:
- cc hello.c
- gcc -O -Wall hello.c
Machines to compile on:
- linux machines (en-2036)
- garfield (a DEC alpha)
- Suns (e.g., maple, mercury)
not a complete ANSI C environment - you will get some warnings
To start the debugger:
- Compile with: gcc -g hello.c
(i.e., don't use the -O option)
- gdb a.out
See the web page for more details on using the compiler and debugger.
More on Strings
Variable definition char buf[1024]:
- sets aside memory for 1024 chars
- value of buf is start (address) of this memory
- value of buf is fixed (can't be changed)
- sizeof(buf) returns
# of elements * size of an element
- initial contents of memory is undefined (local variables)
or 0 (global and static variables)
Variable definition char *ptr:
- sets aside memory for one address
- value of ptr is the address stored in the variable
- can point to any memory
- sizeof(ptr) returns number bytes needed to store an address
- initial value is undefined (local variables) or 0 (global and static variables)
String routines
- char *strcpy(char *dst, char *src)
- int strlen(char *str)
- int strcmp(char *str1, char *str2)
- char *strcat(char *dst, char *src)
- char *strchr(char *str, char c)
- char *strrchr(char *str, char c)
- char *strdup(char *str)
- char *strncpy(char *dst, char *src, int maxlen)
- int strncmp(char *str1, char *str2, int maxlen)
- char *strncat(char *dst, char *src, int maxlen)
Note: only strdup() `creates' new memory!
All others use memory that is passed to them.
Logic Operators
- a && b
- a || b
- !a
- operands can be any scalar type
- lazy evaluation used
- evaluate to 0 or 1
Comparison Operators
- i < j
- i > j
- i <= 0
- i >= 10
- i == 0
- i != 10
- don't use = for comparison
- operands can be int, float or pointers
- avoid using ==,!= on floats
Arithmetic Operators
- i + j
- i - j
- i * j
- i / j
- i % j
- +i
- -i
- ++i, i++
- --i, i--
- operands can be int or float
(% can't take float)
- can add, subtract int from pointer
Assignment Operators
- i = j
- += -= *= /= %=
- &= |= ^= <<= >>=
- evaluate right to left
Misc Operators
- a, b
- a ? b : c
- ? : evaluates right to left
Program fragment:
factorial = 1;
for (i = 0; i < 10; i++) {
if (i)
factorial *= i;
printf("factorial of %d is %d\n",
i, factorial);
}
Modified program fragment:
for (factorial = 1, i = 0; i < 10; i++) {
factorial *= i ? i : 1;
printf("factorial of %d is %d\n",
i, factorial);
}
Bit Operators
- i & j bitwise and
- i | j bitwise or
- i ^ j bitwise exclusive or
- i << j shift i left by j bits
- i >> j shift i right by j bits
- ~i complement (flips all bits)
all operands must be int
[Previous Lecture]
[Lecture Index]
[Next Lecture]