Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions with parameters & results very basic arrays no pointers or structures no string variables (just literal strings) Chapter 1 of C text: overview, don't have to know all details Chapter 2: types, operators & expressions may skip enum constants bitwise operators may be new: please note Chapter 3: control flow may skip: switch, do-while loops Chapter 4: functions (skip section 4.7) Section 7.2 & 7.4: printf & scanf 1 2 "goto Considered Harmful" History Text mentions goto statements in Chapter 3. DO NOT USE!!! Automatic style deduction even on quizzes & final exam. Programming languages evolve! BCPL Β C C++ Java object-oriented 3 4
Versions of C C is an older language & has evolved. Many versions. ANSI C: a standard Most compilers are more flexible than ANSI Rule for this term: Your programs must work using the GNU C compiler. No special flags required. Caution: Make sure your C programs work on the CASLab system. Some other systems use an older compiler Differences Between C and C++ 1. Obvious big difference: no classes in C. Structures only (we'll review later) 2. Some syntax rules are more restrictive in C 3. I/O is different. 4. Different libraries to include 5. Memory allocation is different (later) 6. No bool type 5 6 Compiling and Running a C Program (1) Compiling and Running a C Program (2) For now: one-file programs. File extension must be.c Suppose my program is hello.c To get a nicer name for executable: gcc -o greeting hello.c Now executable file is called greeting (no extension) gcc command: GNU Compiler Collection File extension tells compiler which language. Simplest way to compile & run: gcc hello.c Produces an executable file called a.out. 7 8
Compiling and Running a C Program (3) Two-step method: gcc -c hello.c Compiles only. Does not link. Produces hello.o ("object code") To get an executable (link object code with C library): gcc -o greeting hello.o Warnings Recommended flag for gcc: -Wall Enables many helpful warnings. Examples: single = inside a conditional wrong number of arguments for printf or scanf forgetting to return a value from a function that's not void unused variables Not required for CISC 220, but very helpful in debugging. Suggestion: alias gcc="gcc -Wall" 9 10 One-Line Comments Strict ANSI C: no one-line comments (//) All comments are /*... */ gcc compiler allows one-line comments, so OK to use for CISC 220. Control Structures Just like Java: if, while, for One difference with for loops: In C++ & Java, OK to declare for loop counters in loop: for (int i = 1; i <= 10; i++)... Standard C does not allow this. Instead: int i; for (i = 1; i <= 10; i++)... 11 12
Booleans Signed vs. Unsigned No bool/boolean type in C. Results of tests are integers. 0 = false non-zero = true Be very careful about "=" vs "==": int x = 2; if (x = 3) printf("yes"); else printf("no"); printf("%d\n",x); Integers may be specified signed or unsigned. Default is signed. Integers on CASLab: 4 bytes (32 bits) Signed integer on CASLab: -2 31 to 2 31-1 Unsigned integer on CASLab: 0 to 2 32-1 13 14 Bitwise Operations in C Example: File Protections Logical operators on sequences of bits. View an integer as a string of booleans -- each bit is true (1) or false (0). &: bitwise and : bitwise or ~: bitwise not ("one's complement") 0110 1100 = 1110 0110 & 1100 = 0100 ~0110 = 1001 Goal: store read/write/execute protection for a file in one integer (instead of three separate integers) #define READ 4 #define WRITE 2 #define EXECUTE 1 int main() { int file1perm = READ WRITE; int file2perm = READ EXECUTE; int common = file1perm & file2perm; // remove write permission from file1 file1perm = file1perm & ~WRITE; 15 16
Integer Division Rules: arithmetic between two ints: result is an int (division is truncated) arithmetic between int & float or two floats: result is a float (no truncation) use "(float)" to cast an int into a float printf C++ programmers: The >> operator is part of C++, not C. To write characters to the screen (standard output) in C, use the printf function. Simple use to write a message: printf("hello, world\n"); Ending with \n is important: no equivalent of Java's println. 17 18 printf Conversion Specifications printf Field Widths: Integer To include the value of a variable in output, use special conversion codes in first parameter: %d: integer (d for "decimal", not "double"!) %u: unsigned int %ld: long %lu: unsigned long %f: float or double %c: single character %s: string Example: int x =...; float y =...; printf("the answers are %d and %f\n", x, y); May put minimum field width after a %: printf("%5d\n", num); pads with left blanks if necessary 19 20
printf Field Widths: floating point For float and double, may also specify a precision: printf("%8.2f\n", x); Minimum of 8 characters total Exactly two digits after decimal point scanf Reads from the standard input. Conversion specifications similar to print, not exactly the same! type printf scanf char %c %c int %d %d float %f %f double %f %lf Return value from scanf: EOF if hit end of file before reading values otherwise, number of values read 21 22 Portability Issues Sizes of numeric types differ, depending on compiler & target machine. C arithmetic is not portable! sizeof(type): number of bytes used by the type <limits.h>: contains constants giving max & min values for the integer types <float.h>: constants relating to floating-point types Look at sizes.c... Floating-Point Types Basic floating-point type: float Other types: double, long double All floating point numbers are signed. 23 24
Arrays (quick preview) To create an array of 20 integers: int nums[20]; Things to note: no "new" array elements are not initialized no ".length" C Functions and Program Structure Reading: Chapter 4 of C text You may skip Section 4.7 (register variables) Included in this sub-topic: functions, parameters and return results multi-file programs the C preprocessor (no macros with arguments) example: array1.c Things to remember array parameters passed by reference (address of array) type of array parameter doesn't include size example: array2.c 25 26 Functions Functions in C very similar to Java/C++ All parameters are passed by value (no "ref" parameters in C) main Function A C program must have a main function. Optional parameters to main: later (command-line args) Return type of main is int: return status. Good practice when writing C programs that may be run in Linux: return 0 for success, non-zero for error aborts To abort a program from a function that's not main: exit(1) (exit function is in <stdlib.h>) 27 28
Order of Declarations In C, every function & variable must be declared before it is used. In smallfunc.c, defined functions in convenient order: each function fully defined before called. Not always possible or convenient: mutual recursion preferences about order of functions in files separate compilation Declaration vs. Definition Declaration of function tells you: name of function return types number and types of parameters A specification: not how the function works but how to use it. Declaration == header only Sometimes called a "forward declaration" Definition of function: full definition, including the body. All details of how the function works. Includes repetition of information from declaration. Definition = header + body 29 30 Global Variables Variables defined outside any functions. Must be declared before use. Use with caution: can make program much less readable! Example: add global count & accuracy to smallfuncs.c The C Pre-processor Two phases of C compilation: source code pre-processor modified source code compiler object code 31 32
Pre-Processor Language Every line starting with "#" is a command to the pre-processor. Important: Pre-processor syntax C syntax! To run pre-processor by itself: cpp P <filename> #define (note: We're skipping macros with arguments section 6.3.3) #include #undef #if #ifdef #ifndef #else #elif #endif Pre-Processor Directives examples... 33 34 Notes and Reminders #include's can nest to any depth Preprocessor will complain if you define something that's already defined use #undef first (or check with #ifdef) #if/#ifdef useful to comment out a block of code temporarily (avoids problems with nested comments) #if & #ifdef also useful to implement different "modes" for example debugging and non-debugging mode, or linux and Windows mode arithmetic in #if expressions is integer arithmetic #include <filename>: look in system directories #include "filename": look in current directory Pre-Processor Definitions with gcc gcc -DNAME=VALUE program.c Caution: if NAME is already defined in program.c you'll get a warning. 35 36
Separating Programs Into Files Java: very simple, by classes. C: program is a sequence of definitions (mostly functions) separate definitions into multiple files no automatic scheme for where to find functions Why Multiple Files? 1. Large programs: faster compilation *** 2. Logical organization related definitions grouped together 3. Working in groups each programming editing a different file 4. Library files definitions useful in more than one program *** Goal: be able to compile each file separately. Later, link compiled portions of program together. 37 38 module.h: void func1(int x); int func2(float y); program.c: #include "module.h"... int main() {.. func1(17); z = func2(3.4); } /* end main */ Usual Style module.c: #include module.h void func1(int x) {... (function body) } int func2(float y) {... (function body) } Demonstration Split smallfuncs.c into several files: one file contains input function another file contains square root function and helpers other file contains main function 39 40
To Compile One File a Partial Program To Link a Program Together gcc Wall c module.c Can use gcc to link several object files together: Output is module.o: object code machine code with some pieces unspecified (i.e. references to other parts of the program) gcc o program file1.o file2.o file3.o executable file created by combining all the object code & resolving references between them 41 42 Possible Changes to Demo Program 1. Change square root function (use different algorithm) 2. Change detail in main file 3. Add a second parameter to the square root function 4. Add cube root function (used by main) 43