970 likes | 1.18k Views
Introduction to C (with a Bit of C++ Syntax). Doug Sondak SCV sondak@bu.edu. Outline. Goals C/C++ History Basic syntax makefiles Additional syntax . Goals. To be able to write simple C (C++) programs To be able to understand and modify existing C code
E N D
Introduction to C (with a Bit of C++ Syntax) Doug Sondak SCV sondak@bu.edu
Outline • Goals • C/C++ History • Basic syntax • makefiles • Additional syntax
Goals • To be able to write simple C (C++) programs • To be able to understand and modify existing C code • To be able to write and use makefiles
C History • Developed by Dennis Ritchie at Bell Labs in 1972 • Originally designed for system software • Impetus was porting of Unix to a DEC PDP-11 • PDP-11 had 24kB main memory! • 1978 book “The C Programming Language” by Kernighan & Ritchie served as standard • Official ANSI standard published in 1989 • Updated in 1999
C++ History • C++ was developed by BjarneStroustrup at Bell Labs in 1979 • implemented object-oriented features of another language, “Simula,” in C • originally called “C with Classes” • name changed to C++ in 1983 • first commercial compiler in 1985 • official standard published in 1988
C vs. C++ • C is essentially a subset of C++ • There are some minor “convenience features” in C++ that we will utilize here • Here we will use the GNU C++ compiler g++ • Since we will be writing rudimentary codes, we will not get into object-oriented constructs
C/C++ Syntax • Source lines end with semicolons (as in Matlab) • Case-sensitive • Spaces don’t matter except within literal character strings • I use them liberally to make code easy to read • Comments • C: enclosed by /* */ • C++: // at beginning of comment • many C compilers also accept this syntax
C/C++ Syntax (cont’d) • Declarations – must declare each variable as being integer, floating-point, character, etc. • Required because different types are represented differently internally • Since integers have no decimal places, integer arithmetic will truncate result • If i=3 and k=2, i/k=1, k/i=0 • Program blocks are enclosed within { } • Source file suffix • C: .c • C++: usually .cc or .C
C/C++ Syntax (3) • Simple programs consist of functions and header files • Main program is a function called main (surprise!) • Functions have return types (int, float, etc.) • even if they don’t return anything • Main function is defined by the return type, the word main followed by any arguments within parenthesis, followed by the function statements within {} int main(){ function statements } function name type declaration function arguments (we have no arguments here but still need parentheses)
C/C++ Syntax (4) • Style note: some people like to arrange the brackets like int main() { function statements } • Either way is fine • Be consistent!
C/C++ Syntax (5) • Header files contain re-usable code elements • Function definitions, variable declarations, etc. • Sometimes use system header files • Sometimes you write them yourself • In C usually have a .h suffix, may not in C++ #include <header_file_name.h> • Included before function definition • Note that the #include statement does not end with a ;
C/C++ Syntax (6) • A character string is enclosed by double quotes • Characters within the quotes will be taken literally “This is my character string.” • Single character is enclosed in single quotes ‘h’
C/C++ Syntax (7) • coutis a stream that is used to direct output to the screen, e.g. cout << “my string”; • sends the string to cout, i.e., to the screen • The above syntax does not include a carriage return at the end of the line. We can add the carriage return with: cout << “my string” << endl;
C/C++ Syntax (8) • In C and C++ many standard functions, variables, streams, etc. are defined in header files. • If you want to use these variables, etc., you must include the appropriate header file in your code • C++ (but not C) has a feature, namespace, that defines packages of functions, etc. • This is fairly new, and you might not see it in older C++ programs
C/C++ Syntax (9) • The cout stream is defined in the iostreamheader file, which is part of the “std” namespace • The syntax to use the std namespace is using namespace std;
Exercise 1 • Write a “hello world” program in an editor • Program should print a character string • General structure of code, in order: • include iostream (see slide 11) • not iostream.h, just “iostream” • use the “std” namespace (see slide 15) • define main function (see slide 9) • use cout and endl to print string to screen (see slide 13) • Save it to the file name hello.cc • solution
Compilation • A compiler is a program that reads source code and converts it to a form usable by the computer • Code compiled for a given type of processor will not generally run on other types • AMD and Intel are compatible • We’ll use g++, since it’s free and ubiquitous
Compilation (cont’d) • Compilers have huge numbers of options • See gcc compiler documentation at http://gcc.gnu.org/onlinedocs/ • gcc refers to the “GNU compiler collection,” which includes the C compiler (gcc) and the C++ compiler (g++) • For now, we will simply use the –o option, which allows you to specify the name of the resulting executable
Compilation (3) • In a Unix window: g++ –o hello hello.cc • Compile your code • If it simply returns a Unix prompt it worked • If you get error messages, read them carefully and see if you can fix the source code and re-compile
Compilation (4) • Unlike all other compilers I’ve used (gcc, gfortran, pgcc, etc.), g++ automatically adds a .exe suffix to your specified executable name • hello.exe • Once it compiles correctly, type ./hello.exe at the Unix prompt, and it will print your string
Declarations • Lists of variables with their associated types • C compilers usually require that they come before any executable statements • C++ compilers allow them anywhere, often at the first use of the variable • Basic types: • int • Usually 4 bytes • float • Usually 4 bytes • double • Usually 8 bytes • char • Single character • One byte
Declarations (cont’d) • Examples: inti, j, k; float xval, time; char name, date; • A “char” variable represents a single character
Arithmetic • +, -, *, / • No power operator (see next bullet) • Math functions in math.h • pow(x,y) raises x to the y power • sin, acos, tanh, exp, sqrt, etc. • add –lm flag to compile command to access math library • Exponential notation indicated by letter “e” 4.2e3 • Goodpractice to use decimal points with floats, e.g., x = 1.0 rather than x = 1
Arithmetic (cont’d) • ++ and -- operators • these are equivalent: i = i+1; i++; • always increment/decrement by 1 • += • these are equivalent: x = x + 46.3*y; x += 46.3*y;
Arithmetic (3) • Can convert types with cast operator float xval; inti, j; xval = (float) i / (float) j;
Exercise 2 • Write program to convert a Celcius temperature to Fahrenheit and print the result. • Hard-wire the Celcius value to 100.0 • We’ll make it an input value in a subsequent exercise • Don’t forget to declare all variables F = (9/5)C + 32 • solution
cin • cinreads input from the screen cin >> var; • Note: >> rather than << as with cout • Writes input value to variable var • Often use cout and cin to prompt for a value: cout << “Enter value: ”; cin >> x;
Exercise 3 • Modify Celcius program to read value from keyboard • Prompt for value using cout • Read value using cin • Rest can remain the same as last exercise • solution
Arrays • Can declare arrays using [ ] float x[100]; char a[25]; • Array indices start at zero • Declaration of x above creates locations for x[0] through x[99] • Multiple-dimension arrays are declared as follows: int a[10][20];
Arrays (cont’d) • Character strings (char arrays) always end with the character \0 • You usually don’t have to worry about it as long as you dimension the string 1 larger than the length of the required string char name[5]; name = “Fred”; char name[4]; name = “Fred”; works doesn’t work
For Loop • for loop repeats calculation over range of indices for(i=0; i<n; i++){ a[i] = sqrt( pow(b[i],2) + pow(c[i],2) ) } • for statement has 3 parts: • initialization • completion condition • what to do after each iteration
Exercise 4 • Write program to: • declare two vectors of length 3 • prompt for vector values • calculate dot product • print the result • solution
Pointers • Memory is organized in units of words • Word size is architecture-dependent • Pentium 4 bytes • Xeon, Itanium 8 bytes • Each word has a numerical address 32 16 8 0
Pointers (cont’d) • When you declare a variable, a location of appropriate size is reserved in memory • When you set its value, the value is placed in that memory location 32 float x; 3.2 x = 3.2; 16 8 0 address
Pointers (3) • A pointer is a variable containing a memory address • Declared using * prefix float *p; • Address operator & • Address of specified variable float x, *p; p = &x;
Pointers (4) float x, *p; p = &x; 1056 32 p 1052 16 16 1048 8 1040 0 address address
Pointers (5) • Depending on context, * can also be the dereferencing operator • Value stored in memory location pointed to by specified pointer *p = 3.2; • Common newbie error float *p; *p = 3.2; float x, *p; p = &x; *p = 3.2; Wrong! – p doesn’t have value yet correct
Pointers (6) • The name of an array is actually a pointer to the memory location of the first element • a[100] • “a” is a pointer to the first element of the array (a[0]) • These are equivalent: x[0] = 4.53; *x = 4.53;
Pointers (7) • If p is a pointer and n is an integer, the syntax p+nmeans to advance the pointer by n memory locations • These are therefore equivalent: x[4] = 4.53; *(x+4) = 4.53;
Pointers (8) • In multi-dimensional arrays, values are stored in memory with last index varying most rapidly (a[0][0], a[0][1], … ) • Opposite of Matlab and Fortran • The two statements in each box are equivalent: a[0][17] = 1; a[1][0] = 5; *(a+17) = 1; *(a+20) = 5;
sizeof • Some functions require size of something in bytes • A useful function – sizeof(arg) • The argument arg can be a variable, an array name, a type • Returns no. bytes in arg float x, y[5]; sizeof(x) ( 4) sizeof(y) (20) sizeof(float) ( 4)
Dynamic Allocation • Suppose you need an array, but you don’t know how big it needs to be until run time. • Use malloc function malloc(n) • n is no. bytes to be allocated • returns pointer to allocated space • lives in stdlib.h
Dynamic Allocation (cont’d) • Declare pointer of required type float *myarray; • Suppose we need 101 elements in array • malloc requires no. bytes, cast as appropriate pointer myarray = (float *) malloc(101*sizeof(float)); • free releases space when it’s no longer needed: free(myarray);
Exercise 5 • Modify dot-product program to handle vectors of any length • Prompt for length of vectors • Read length of vectors from screen • Dynamically allocate vectors • Don’t forget to include stdlib.h so you have access to the malloc function • solution
if/else if/else • Conditional execution of block of source code • Based on relational operators < less than > greater than == equal <= less than or equal >= greater than or equal != not equal && and || or
if/else if/else (cont’d) if( x > 0.0 && y > 0.0 ){ z = 1.0/(x+y); }else if( x < 0.0 && y < 0.0){ z = -1.0/(x+y); }else{ printf(“Error condition\n”); }
if/else if/else (3) • Can use “if” without “else” if( x > 0.0 && y > 0.0 ){ printf(“x and y are both positive\n”); }
Exercise 6 • In dot product code, check if the magnitude of the dot product is less than using the absolute value function fabsf. If it is, print a warning message. • With some compilers you would need to include math.h for the abs function • With some compilers you would need to link to the math library by adding the flag –lm to the end of your compile/link command • solution
Functions • Function returns a single object (number, array, etc.) • Return type must be declared • Argument types must be declared • Sample function definition: float sumsqr(float x, float y){ float z; z = x*x + y*y; return z; }
Functions (cont’d) • Use of sumsqr function: a = sumsqr(b,c); • Call by value • when function is called, copies are made of the arguments • scope of copies is scope of function • after return from function, copies no longer exist