A Quick Look at C for C++ Programmers

Post on 07-Feb-2016

66 views 0 download

Tags:

description

COMP 40: Machine Structure and Assembly Language Programming (Fall 2014 ). A Quick Look at C for C++ Programmers. Noah Mendelsohn Tufts University Email: noah@cs.tufts.edu Web: http://www.cs.tufts.edu/~noah. Let’s look at some code. Hello world compared. #include < iostream > - PowerPoint PPT Presentation

Transcript of A Quick Look at C for C++ Programmers

A Quick Look at Cfor

C++ Programmers

Noah Mendelsohn (with updates by Mark Sheldon)Tufts University Email: noah@cs.tufts.eduWeb: http://www.cs.tufts.edu/~noah

COMP 40: Machine Structure and

Assembly Language Programming (Spring 2016)

© 2010 Noah Mendelsohn

Let’s look at some code

© 2010 Noah Mendelsohn

Hello world compared

3

#include <iostream>#include <string>

using namespace std;

int main(int argc, char *argv[]){ string world = "world"; cout << "Hello " << world << endl;}

C++

#include <stdio.h>#include <stdlib.h>

int main(int argc, char *argv[]){

char *world = "world";

printf("Hello %s\n", world); return EXIT_SUCCESS; }

C

© 2010 Noah Mendelsohn

Hello world compared

4

#include <iostream>#include <string>

using namespace std;

int main(int argc, char *argv[]){ string world = "world"; cout << "Hello " << world << endl;}

#include <stdio.h>#include <stdlib.h>

int main(int argc, char *argv[]){

char *world = "world";

printf("Hello %s\n", world); return EXIT_SUCCESS; }

C++ C

No namespaces in C

© 2010 Noah Mendelsohn

Hello world compared

5

#include <iostream>#include <string>

using namespace std;

intmain(int argc, char *argv[]){ string world = "world"; cout << "Hello " << world << endl;}

#include <stdio.h>

intmain(int argc, char *argv[]){

char world[] = "world";

printf("Hello %s\n", world); return 0; }

C++ C

C++: stream I/O w/coutC: stdio with stdout, printf, etc.

© 2010 Noah Mendelsohn

Hello world compared

6

#include <iostream>#include <string>

using namespace std;

int main(int argc, char *argv[]){ string world = "world"; cout << "Hello " << world << endl;}

#include <stdio.h>#include <stdlib.h>

int main(int argc, char *argv[]){

char *world = "world";

printf("Hello %s\n", world); return EXIT_SUCCESS; }

C++ C

Format string allows substitution

© 2010 Noah Mendelsohn

Hello world compared

7

#include <iostream>#include <string>

using namespace std;

intmain(int argc, char *argv[]){ string world = "world"; cout << "Hello " << world << endl;}

#include <stdio.h>#include <stdlib.h>

int main(int argc, char *argv[]){

char *world = "world";

printf("Hello %s\n", world); return EXIT_SUCCESS; }

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)%-10s – string (10 chars left justified)Etc, etc.

© 2010 Noah Mendelsohn

Hello world compared

8

#include <iostream>#include <string>

using namespace std;

int main(int argc, char *argv[]){ string world = "world"; cout << "Hello " << world << endl;}

#include <stdio.h>#include <stdlib.h>

int main(int argc, char *argv[]){

char *world = "world";

printf("Hello %s\n", world); return EXIT_SUCCESS; }

C++ C

\n = new line char\t = tab char\\ = \ charEtc.

© 2010 Noah Mendelsohn

Basic Datatypes

© 2010 Noah Mendelsohn

C and C++ mostly share basic data types

10

char a single byte, capable of holdingone character in the local character set.

int an integer, typically reflecting thenatural size of integers on the host machine.

short int an integer, possibly smaller than int

long int an integer, possibly longer than intlong 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 integerint y; variable y holds an integerint 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);

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 integerint y; variable y holds an integerint 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

16

#include <stdio.h>

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 <stdio.h>#include <stdlib.h>

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 EXIT_SUCCESS; }

C has structs, not classes

structs have data only…no methods!

© 2010 Noah Mendelsohn

Some structured data

18

#include <stdio.h>#include <stdlib.h>

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 EXIT_SUCCESS; }

Unlike C++: keyword struct required when naming a structured type

© 2010 Noah Mendelsohn

Some structured data

19

#include <stdio.h>#include <stdlib.h>

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 EXIT_SUCCESS; }

Initializers more or less the same as C++

© 2010 Noah Mendelsohn

Some structured data

20

#include <stdio.h>#include <stdlib.h>

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 EXIT_SUCCESS; }

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 <stdio.h>#include <stdlib.h>

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 EXIT_SUCCESS; }

You will want to learn about printf and fprintf format

specifications

© 2010 Noah Mendelsohn

Good Practice:Single Point of Truth

© 2010 Noah Mendelsohn

#include <stdio.h>intmain(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?

Single point of truth

23

© 2010 Noah Mendelsohn

24

#include <stdio.h>intmain(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?

Single point of truth

© 2010 Noah Mendelsohn

Single point of truth

25

#include <stdio.h>#include <stdlib.h>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 EXIT_SUCCESS; }

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

Single point of truth

26

#include <stdio.h>#include <stdlib.h>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 EXIT_SUCCESS; }

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!

Caution: sizeof works this way for arrays only when in the same scopeas the array declaration!

© 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

29

© 2010 Noah Mendelsohn

C vs C++ File I/O

© 2010 Noah Mendelsohn

Access to files and inputFeature C C++Pre-opened streams stdin, stdout,

stderrcin, 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!”;

31

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 of myprog is output of otherprog

© 2010 Noah Mendelsohn

More about C Strings

© 2010 Noah Mendelsohn

C characters

33

#include <stdio.h>#include <stdlib.h>

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

34

#include <stdio.h>#include <stdlib.h>

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 78The number for O is 79The number for A is 65The number for H is 72

© 2010 Noah Mendelsohn

C characters are integers!

35

#include <stdio.h>#include <stdlib.h>

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 78The number for O is 79The number for A is 65The number for H is 72

Interesting…Characters are also numbers!

© 2010 Noah Mendelsohn

Hello world compared

36

C++: string type

#include <iostream>#include <string>

using namespace std;

intmain(int argc, char *argv[]){ string world = "world"; cout << "Hello " << world << endl;}

C: arrays of characters

#include <stdio.h>#include <stdlib.h>

int main(int argc, char *argv[]){

char world[] = "world";

printf("Hello %s\n", world); return EXIT_SUCCESS; }

C++ C

© 2010 Noah Mendelsohn

Our first hello world

37

#include <stdio.h>#inlcude <stdlib.h>

int main(int argc, char *argv[]){

char world[] = "world";

printf("Hello %s\n", world); return EXIT_SUCCESS; }

String literal gives array of characters

© 2010 Noah Mendelsohn

C arrays addressed by pointer to first element

38

#include <stdio.h>#include <stdlib.h>

int main(int argc, char *argv[]){

char *world = "world";char universe[] = “universe”;

printf("Hello %s\n", world);printf("Hello %s\n", universe);

return EXIT_SUCCESS; }

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

39

#include <stdio.h>#include <stdlib.h>#include <string.h>

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 EXIT_SUCCESS; }

What does this print?

© 2010 Noah Mendelsohn

If you understand this, you’re well on your way!

40

#include <stdio.h>#include <stdlib.h>#include <string.h>

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 EXIT_SUCCESS; }

What does this print?

© 2010 Noah Mendelsohn

If you understand this, you’re well on your way!

41

#include <stdio.h>#include <stdlib.h>#include <string.h>

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 EXIT_SUCCESS; }

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 this3) In a correct program, there should be at least enough space for the string, but you may have allocated more4) 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 allocates and initializes objects:

– Car *myCar = new Car(V8, Blue); // Create a new car • The above allocates space and initializes all the data for mycar

– 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

43

© 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 *car_p = malloc(sizeof struct car);• allocate unitialized bytes

– struct car *car_p = malloc(sizeof *carp);• Same, but keeps working if structure name changes: single point of truth!• You must check the return value to make sure it worked!

– free(car_p); /* frees the bytes */

44

© 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 *car_p = malloc(sizeof struct car);• allocate unitialized bytes

– struct car *car_p = malloc(sizeof *carp);• Same, but keeps working if structure name changes: single point of truth!• You must check the return value to make sure it worked!

– free(car_p); /* frees the bytes */

45

Rule of thumb: The first statement after a call to malloc handles NULL

© 2010 Noah Mendelsohn

A Bit of History

© 2010 Noah Mendelsohn

C++ is an extension to C C was invented many years earlier (c. 1970) C is a quite small language; C++ is much more complicated C is much closer to the hardware, why we’re using it!

– Good programmers know how each C construct compiles– No single C expression compiles to huge amounts of code

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, IO

streams (in the C++ sense), inheritance, built in higher level ADTs (list, vector, deque, table, etc.)

47