1 / 97

Introduction to C (with a Bit of C++ Syntax)

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

hunter
Download Presentation

Introduction to C (with a Bit of C++ Syntax)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to C (with a Bit of C++ Syntax) Doug Sondak SCV sondak@bu.edu

  2. Outline • Goals • C/C++ History • Basic syntax • makefiles • Additional syntax

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. 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)

  10. C/C++ Syntax (4) • Style note: some people like to arrange the brackets like int main() { function statements } • Either way is fine • Be consistent!

  11. 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 ;

  12. 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’

  13. 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;

  14. 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

  15. 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;

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

  22. Declarations (cont’d) • Examples: inti, j, k; float xval, time; char name, date; • A “char” variable represents a single character

  23. 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

  24. 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;

  25. Arithmetic (3) • Can convert types with cast operator float xval; inti, j; xval = (float) i / (float) j;

  26. 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

  27. 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;

  28. 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

  29. 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];

  30. 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

  31. 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

  32. Exercise 4 • Write program to: • declare two vectors of length 3 • prompt for vector values • calculate dot product • print the result • solution

  33. 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

  34. 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

  35. 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;

  36. Pointers (4) float x, *p; p = &x; 1056 32 p 1052 16 16 1048 8 1040 0 address address

  37. 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

  38. 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;

  39. 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;

  40. 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;

  41. 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)

  42. 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

  43. 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);

  44. 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

  45. 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

  46. 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”); }

  47. 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”); }

  48. 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

  49. 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; }

  50. 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

More Related