A Quick Look at C for C++ Programmers Noah Mendelsohn Tufts University Web: COMP.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
MPI and C-Language Seminars Seminar Plan (1/3)  Aim: Introduce the ‘C’ Programming Language.  Plan to cover: Basic C, and programming techniques.
C Programming Day 1 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
The little language that could Remember C is a “small language”
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
C++ crash course Class 3 designing C++ programs, classes, control structures.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
Input & Output: Console
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
PRIMITIVE DATA TYPES -Integer -Floating Point -Decimal -Boolean -Character STRINGS -Character Array -Class -String Length -Static -Limited Dynamic -Dynamic.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
ITEC 320 C++ Examples.
1 C++ Syntax and Semantics, and the Program Development Process.
Chapter 10C++ for Java Programmers1 Chapter 10 Input/Output.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Pointers OVERVIEW.
More on Abstract Data Types Noah Mendelsohn Tufts University Web: COMP 40: Machine.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Characters and Strings File Processing Exercise C Programming:Part 3.
Dynamic memory allocation and Pointers Lecture 4.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
Fundamentals of C++ Yingcai Xiao 09/03/08. Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation.
Big Endian vs. Little Endian Storage of Numeric Data Noah Mendelsohn Tufts University Web:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
C LANGUAGE Characteristics of C · Small size
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 7 – Introduction to C: The C Level of Abstraction.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
More on Abstract Data Types Noah Mendelsohn and Mark Sheldon Tufts University Web:
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
C is a high level language (HLL)
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Hank Childs, University of Oregon April 15 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
Lecture 3: Getting Started & Input / Output (I/O)
CSE 374 Programming Concepts & Tools
The Machine Model Memory
C Primer.
CSE 374 Programming Concepts & Tools
A bit of C programming Lecture 3 Uli Raich.
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Command Line Arguments
An Introduction to C Programming
C Basics.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Programming in C Input / Output.
Computer Science 210 Computer Organization
Programming in C Input / Output.
Pointers, Dynamic Data, and Reference Types
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Programming in C Input / Output.
Programming in C Pointers and Arrays.
Introduction to C EECS May 2019.
15213 C Primer 17 September 2002.
Extra C Material Based on material in: The C Programming Language, Second Edition by Brian W. Kernighan and Dennis M. Ritchie. Prentice Hall, Inc., 1988. 
Presentation transcript:

A Quick Look at C for C++ Programmers Noah Mendelsohn Tufts University Web: COMP 40: Machine Structure and Assembly Language Programming (Fall 2014)

© 2010 Noah Mendelsohn Let’s look at some code

© 2010 Noah Mendelsohn Hello world compared 3 #include using namespace std; int main(int argc, char *argv[]) { string world = "world"; cout << "Hello " << world << endl; } C++ #include int main(int argc, char *argv[]) { char *world = "world"; printf("Hello %s\n", world); return 0; } C

© 2010 Noah Mendelsohn Hello world compared 4 #include using namespace std; int main(int argc, char *argv[]) { string world = "world"; cout << "Hello " << world << endl; } #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); return 0; } C++C No namespaces in C

© 2010 Noah Mendelsohn Hello world compared 5 #include using namespace std; int main(int argc, char *argv[]) { string world = "world"; cout << "Hello " << world << endl; } #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); return 0; } C++C C++: stream I/O w/cout C: stdio with stdout, printf, etc.

© 2010 Noah Mendelsohn Hello world compared 6 #include using namespace std; int main(int argc, char *argv[]) { string world = "world"; cout << "Hello " << world << endl; } #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); return 0; } C++C Format string allows substitution

© 2010 Noah Mendelsohn Hello world compared 7 #include using namespace std; int main(int argc, char *argv[]) { string world = "world"; cout << "Hello " << world << endl; } #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); return 0; } C++C Format strings: %s – string %d – integer (decimal, signed) %u – integer (decimal, unsigned) %ld – integer (decimal, long) %x – integer (base 16 hex) %c – single ASCII character %5d – integer (5 chars wide) Etc, etc.

© 2010 Noah Mendelsohn Hello world compared 8 #include using namespace std; int main(int argc, char *argv[]) { string world = "world"; cout << "Hello " << world << endl; } #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); return 0; } C++C \n = new line char \t = tab char \\ = \ char Etc.

© 2010 Noah Mendelsohn Basic Datatypes

© 2010 Noah Mendelsohn C and C++ mostly share basic data types 10 char a single byte, capable of holding one character in the local character set. int an integer, typically reflecting the natural size of integers on the host machine. short int an integer, possibly smaller than int long int an integer, possibly longer than int long long int an integer, possibly longer than long float single-precision floating point. double double-precision floating point. Abbreviations: “ short ” is same as “ short int ”; “ long ” same as “ long int ” Examples: int x; short int s; short s; double gpa;

© 2010 Noah Mendelsohn Pointers 11 char c; /* a single byte character */ char *cp; /* a pointer to a single byte character */ A pointer variable holds a reference to some other variable.

© 2010 Noah Mendelsohn What does this code do? 12 int x; /* variable x holds an integer */ int y; /* variable y holds an integer */ int z; /* variable z holds an integer */ int *iptr; /* variable iptr holds pointer to an integer */ x = 2; y = 3; ip = &z; *ip = x + y; printf(“First answer is %d\n”, z); If you’re not sure, try this code yourself. Try changing it!

© 2010 Noah Mendelsohn What does this code do? 13 int x; /* variable x holds an integer */ int y; /* variable y holds an integer */ int z; /* variable z holds an integer */ int *ip; /* variable ip holds pointer to an integer */ x = 2; y = 3; ip = &z; *ip = x + y; printf(“First answer is %d\n”, z); *ip = *ip + z; printf(“Seconed answer is %d\n”, z); If you’re not sure, try this code yourself. Try changing it!

© 2010 Noah Mendelsohn Structured Data

© 2010 Noah Mendelsohn Some structured data 15 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[ ] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } Primitive types mostly the same as C++

© 2010 Noah Mendelsohn Some structured data 16 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[3] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; }

© 2010 Noah Mendelsohn Some structured data 17 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[3] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } C has structs, not classes structs have data only…no methods!

© 2010 Noah Mendelsohn Some structured data 18 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[3] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } Unlike C++: keyword struct required when naming a structured type

© 2010 Noah Mendelsohn Some structured data 19 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[3] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } Initializers more or less the same as C++

© 2010 Noah Mendelsohn Some structured data 20 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[ ] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } We can leave out array bound if initializer determines the size – same as C++

© 2010 Noah Mendelsohn You saw printf and format strings earlier! 21 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[ ] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } You will want to learn about printf and fprintf format specifications

© 2010 Noah Mendelsohn Good Practice: Single Point of Truth

© 2010 Noah Mendelsohn Single point of truth 23 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[ ] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } What’s going on here?

© 2010 Noah Mendelsohn Single point of truth 24 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[ ] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, {“albert", 22}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } What if number of students changes?

© 2010 Noah Mendelsohn Single point of truth 25 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[ ] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, {“albert", 22}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } There is a single point of truth for the number of students Try to have single points of truth for anything in your program that’s likely to change, or on which multiple other things depend…if we change this structure, everything just works!

© 2010 Noah Mendelsohn …BTW: this is the same as C++ 26 #include int main(int argc, char *argv[]) { struct student { char *name; int age; }; struct student students[ ] = { {"mary", 15}, {"bob", 9}, {"tina", 12}, } ; unsigned int i; (void)argc; (void)argv; for (i=0; i < sizeof(students) / sizeof(struct student); i++) { printf("Student %s is %d years old.\n", students[i].name, students[i].age); }; return 0; } Suppress compiler warning about unused arguments -- same as C++

© 2010 Noah Mendelsohn Why we use Hanson in COMP 40

© 2010 Noah Mendelsohn What about abstract data types like list, or table?  Many modern languages have them built into the standard –Python, Ruby, etc., etc. –C++ Standard Template Library (STL)  C does not standardize implementation of types like these  Hanson gives us C based ADT implementations that: –Are useful in our programs –Teach us what’s going on in many of those higher level language implementations! –Teach us many good techniques for building modular structures in C 28

© 2010 Noah Mendelsohn C vs C++ File I/O

© 2010 Noah Mendelsohn Access to files and input FeatureCC++ Pre-opened streams stdin, stdout, stderr cin, cout, cerr Open a file FILE *fp fopen(filename,”r”) ifstream myfile(“filename”); Typical use fprintf(stderr, “error\n”); fprintf(fp,”Hi!”); cerr << “error” << endl; myfile << “Hi!”; 30 In both languages: The operating system pre-opens the three standard streams They can be redirected from the command line: myprog < somefile # stdin reads from somefile myprog > somefile # stdout writes to somefile otherprog | myprog # stdin is output of otherprog

© 2010 Noah Mendelsohn More about C Strings

© 2010 Noah Mendelsohn C characters 32 #include int main(int argc, char *argv[]) { (void)argc; (void)argv; unsigned char var1 = 'N'; unsigned char var2 = 'O'; unsigned char var3 = 'A'; unsigned char var4 = 'H'; /* %c prints as character %u prints unsigned integer */ printf("The number for %c is %u\n", var1, var1); printf("The number for %c is %u\n", var2, var2); printf("The number for %c is %u\n", var3, var3); printf("The number for %c is %u\n", var4, var4); exit(EXIT_SUCCESS); } Printing each one twice… …in different formats!

© 2010 Noah Mendelsohn C characters 33 #include int main(int argc, char *argv[]) { (void)argc; (void)argv; unsigned char var1 = 'N'; unsigned char var2 = 'O'; unsigned char var3 = 'A'; unsigned char var4 = 'H'; /* %c prints as character %u prints unsigned integer */ printf("The number for %c is %u\n", var1, var1); printf("The number for %c is %u\n", var2, var2); printf("The number for %c is %u\n", var3, var3); printf("The number for %c is %u\n", var4, var4); exit(EXIT_SUCCESS); } This program prints: The number for N is 78 The number for O is 79 The number for A is 65 The number for H is 72

© 2010 Noah Mendelsohn C characters are integers! 34 #include int main(int argc, char *argv[]) { (void)argc; (void)argv; unsigned char var1 = 'N'; unsigned char var2 = 'O'; unsigned char var3 = 'A'; unsigned char var4 = 'H'; /* %c prints as character %u prints unsigned integer */ printf("The number for %c is %u\n", var1, var1); printf("The number for %c is %u\n", var2, var2); printf("The number for %c is %u\n", var3, var3); printf("The number for %c is %u\n", var4, var4); exit(EXIT_SUCCESS); } This program prints: The number for N is 78 The number for O is 79 The number for A is 65 The number for H is 72 Interesting… Characters are also numbers!

© 2010 Noah Mendelsohn Hello world compared 35 C++: string type #include using namespace std; int main(int argc, char *argv[]) { string world = "world"; cout << "Hello " << world << endl; } C: arrays of characters #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); return 0; } C++C

© 2010 Noah Mendelsohn Our first hello world 36 #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); return 0; } String literal gives array of characters

© 2010 Noah Mendelsohn C arrays addressed by pointer to first element 37 #include int main(int argc, char *argv[]) { char *world = "world"; char universe[] = “universe”; printf("Hello %s\n", world); printf("Hello %s\n", universe); return 0; } These do almost the same thing The relationship between arrays and pointers is subtle & important! This one you need to research using K&R or Harbison & Steele

© 2010 Noah Mendelsohn A trickier hello 38 #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); world[1] = '\0'; printf("Hello %s your string is %d bytes long!\n", world, strlen(world)); return 0; } What does this print?

© 2010 Noah Mendelsohn If you understand this, you’re well on your way! 39 #include int main(int argc, char *argv[]) { char world[] = "world"; printf("Hello %s\n", world); world[1] = '\0'; printf("Hello %s your string is %d bytes long!\n", world, strlen(world)); world[3] = 'm'; printf("Hello %s your string is %d bytes long!\n", world, strlen(world)); world[1] = 'o'; world[4] = '\0'; printf("Hello %s your string is %d bytes long!\n", world, strlen(world)); return 0; } What does this print?

© 2010 Noah Mendelsohn If you understand this, you’re well on your way! 40 #include int main(int argc, char *argv[]) { char *world = "world"; printf("Hello %s\n", world); world[1] = '\0'; printf("Hello %s your string is %d bytes long!\n", world, strlen(world)); world[3] = 'm'; printf("Hello %s your string is %d bytes long!\n", world, strlen(world)); world[1] = 'o'; world[4] = '\0'; printf("Hello %s your string is %d bytes long!\n", world, strlen(world)); return 0; } These examples show that: 1) The logical length of a C string is determined by the terminating null character ‘\0’ 2) Printing using %s and checking length with strlen() respect this 3) In a correct program, there should be at least enough space for the string, but you may have allocated more 4) In buggy programs, you fail to null terminate or index off the end of the allocated space

© 2010 Noah Mendelsohn Memory allocation

© 2010 Noah Mendelsohn There is no new in C!  C++ new builds objects: – Car *myCar = new Car(V8, Blue); // Create a new car The above allocates space and initializes all the data for car – delete myCar; Runs destructors and releases memory –Also: int *ip = new int[len]; // allocate array delete[] ip; // delete array –Also: std:vector // truly dynamic array 42

© 2010 Noah Mendelsohn There is no new in C!  C++ new builds objects: – Car *myCar = new Car(V8, Blue); // Create a new car The above allocates space and initializes all the data for car – delete myCar; Runs destructors and releases memory –Also: int *ip = new int[len]; // allocate array delete[] ip; // delete array –Also: std:vector // truly dynamic array  C malloc/free allocate and free bytes: – struct car { ….members here… }; struct car *carp = malloc(sizeof struct car); allocate unitialized bytes – struct car *carp = malloc(sizeof *carp); Same, but keeps working if structure name changes You should check the return value to make sure it worked! – free(carp); /* frees the bytes */ 43

© 2010 Noah Mendelsohn A Bit of History

© 2010 Noah Mendelsohn C++ is an extension to C  C was invented many years earlier  C is a quite small language; C++ is much more complicated  Most of C survives in C++ –Primitive data types: int, float, double, etc –Control structures (if, while, function call) –Source structures (#include and preprocessor) –Much more  C does not have: –Classes, methods, namespaces, dynamic arrays, dynamic strings, stream I/O, inheritance, built in higher level ADTs (list, vector, deque, table, etc.)  C is much closer to the hardware –Good programmers know how each C construct compiles –No single C expression compiles to huge amounts of code 45