C++ Programmers for A Quick Look at C COMP 40: Machine ...+.pdfC++ C Format specifier allows...
Transcript of C++ Programmers for A Quick Look at C COMP 40: Machine ...+.pdfC++ C Format specifier allows...
-
A Quick Look at Cfor
C++ Programmers
Richard Townsend (Original slides by Noah Mendelsohn, with updates by Mark Sheldon)
Tufts University Email: [email protected]
COMP 40: Machine Structure and
Assembly Language Programming (Fall 2019)
-
© 2010 Noah Mendelsohn
Let’s look at some code
-
© 2010 Noah Mendelsohn
Hello world compared
3
#include #include
using namespace std;
int main(){ string world = "world"; cout
-
© 2010 Noah Mendelsohn
Hello world compared
4
#include #include
using namespace std;
int main(){ string world = "world"; cout
-
© 2010 Noah Mendelsohn
Hello world compared
5
#include #include
using namespace std;
int main(){ string world = "world"; cout
-
© 2010 Noah Mendelsohn
Hello world compared
6
#include
int main(){
char *world = "world";printf("Hello %s\n", world);
}
#include #include
using namespace std;
int main(){ string world = "world"; cout
-
© 2010 Noah Mendelsohn
Hello world compared
7
#include
int main(){
char *world = "world";printf("Hello %s\n", world);
}
#include #include
using namespace std;
int main(){ string world = "world"; cout
-
© 2010 Noah Mendelsohn
Hello world compared
8
#include
int main(){
char *world = "world";printf("Hello %s\n", world);
}
#include #include
using namespace std;
int main(){ string world = "world"; cout
-
© 2010 Noah Mendelsohn
#include
int main(){
char *world = "world";printf("Hello %s\n", world);
}
Hello world compared
9
#include #include
using namespace std;
int main(){ string world = "world"; cout
-
© 2010 Noah Mendelsohn
The string in Hello World
10
#include
int main(){
char *world = "world";printf("Hello %s\n", world);
}
C: arrays of charactersHuh?How come this is a pointer?
In many cases, a reference to a C array turns into a pointer to the first element……using pointers to the beginning of an array is very common in C. Read about this in Kernighan & Ritchie, Section 5.3 (link provided on the class website)!
-
© 2010 Noah Mendelsohn
The string in Hello World
11
#include
int main(){
char *world = "world";char universe[] = “universe”;
printf("Hello %s\n", world);printf("Hello %s\n", universe);
}
These do almost the same thing
The relationship between arrays and pointers is subtle & important!
This one you need to research using K&R (section 5.5).
-
© 2010 Noah Mendelsohn
Basic Datatypes
-
© 2010 Noah Mendelsohn
C and C++ mostly share basic data types
13
char a single byte, capable of holding one 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;
To print size of a type in bytes: printf(“%ul\n”, sizeof(float));
-
© 2010 Noah Mendelsohn
Pointers
14
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?
15
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(“Second answer is %d\n”, z);
-
© 2010 Noah Mendelsohn
More about char and C Strings
-
© 2010 Noah Mendelsohn
C characters
17
#include #include
int main(){
char var1 = 'N';char var2 = 'O';char var3 = 'A';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);
}
Printing each one twice……in different formats!
-
© 2010 Noah Mendelsohn
C characters
18
#include #include
int main(){
char var1 = 'N';char var2 = 'O';char var3 = 'A';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);
}
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!
19
#include #include
int main(){
char var1 = 'N';char var2 = 'O';char var3 = 'A';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);
}
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
A trickier hello
20
#include #include #include
int main(int argc, char *argv[]){
char world[] = "world";
printf("Hello %s\n", world);
world[1] = '\0';
printf("Hello %s your string is %lu bytes long!\n", world, strlen(world));
}
-
© 2010 Noah Mendelsohn
If you understand this, you’re well on your way!
21
#include #include #include
int main(int argc, char *argv[]){
char world[] = "world";printf("Hello %s\n", world);world[1] = '\0';printf("Hello %s your string is %lu bytes long!\n",
world, strlen(world));world[3] = 'm';printf("Hello %s your string is %lu bytes long!\n",
world, strlen(world));world[1] = 'o';world[4] = '\0';printf("Hello %s your string is %lu bytes long!\n",
world, strlen(world));}
What does this print?
-
© 2010 Noah Mendelsohn
If you understand this, you’re well on your way!
22
#include #include #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)); }
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
Structured Data
-
© 2010 Noah Mendelsohn
#include #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); }
}
“Unused Arguments” compiler warnings
24
Suppress compiler warning about unused arguments
--same as C++
-
© 2010 Noah Mendelsohn
Some structured data
25
#include #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); }
}
C has structs, not classes
structs have data only…no methods!
-
© 2010 Noah Mendelsohn
#include #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); }
}
Some structured data
26
Unlike C++: keyword struct required when naming a structured type
-
© 2010 Noah Mendelsohn
#include #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); }
}
Some structured data
27
Initializers more or less the same as C++
-
© 2010 Noah Mendelsohn
#include #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); }
}
Some structured data
28
We can leave out array bound if initializer determines the size –
same as C++
-
© 2010 Noah Mendelsohn
#include #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); }
}
You saw printf and format strings earlier!
29
You will want to learn about
printf and fprintf format specifications
-
© 2010 Noah Mendelsohn
Good Practice:Single Point of Truth
-
© 2010 Noah Mendelsohn
#include #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); }
}
What’s going on here?
Single point of truth
31
-
© 2010 Noah Mendelsohn
#include #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); }
}
Single point of truth
32
What if number of students changes?
-
© 2010 Noah Mendelsohn
#include #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); }
}
Single point of truth
33
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
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
35
-
© 2010 Noah Mendelsohn
C vs C++ File I/O
-
© 2010 Noah Mendelsohn
Access to files and inputFeature C C++Pre-opened streams
stdin, stdout, stderr cin, cout, cerr
Open a file FILE *fp;fp = fopen(filename, ”r”);
ifstream myfile;myfile.open(“filename”);
Typical use fprintf(stderr, ”error\n”);fprintf(fp, ”Hi!”);
cerr
-
© 2010 Noah Mendelsohn
Memory allocation
-
© 2010 Noah Mendelsohn
There is no new in C!▪ C++ 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
39
-
© 2010 Noah Mendelsohn
There is no new in C!▪ C++ 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
40
Rule of thumb: The first statement after a call to
handles
▪ 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 *car_p);• 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 */