C vs C++: Review
We pause one final time at the end of the semester to look at differences that have popped up between C and C++.
As a reminder of the differences we've already covered:
- Compiling
- Compiler is gcc not g++
- Files are named .c not .cpp
- Included libraries are different (C includes stdio.h and stdlib.h)
- Input/Output & Variables
- printf instead of cout
- scanf instead of cin
FILE* instead of ifstream
- There is no string nor bool type
- Arrays and Memory Allocation
- C++ uses
new, but C must use malloc or calloc
- C strings are just char arrays.
Today we'll look at functions, and linked lists. The summary is actually pretty easy:
- Functions
- No function overloading in C.
- Structs and Lists
- Structs must say "struct" in front of the type.
- Otherwise all the same!
Functions
You cannot overload functions in C. Recall that overloading is the
ability to write two functions with the same function name but different
function signatures. This is a very useful thing to do. For example, you might
want two max functions:
int max(int, int);
int max(int, int, int);
This enables the user to find the max of three numbers without having to call
the two-parameter version twice.
Structs
Just a syntax change! Structs are actually a C construct. C++ builds on
structs with something called classes, but we ran out of time to
introduce those. The change here is syntactic, and frankly a little annoying.
You now have to write struct in front of all your type
declarations.
Example code: a linked list
- C++ program:
Here's a C++ program that reads a linked list of strings from the user (stop at
END) and print it: ex.cpp.
- C program:
Below is the C code that works the same as
ex.cpp. Observe that
struct Node is always used instead of
Node.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
char data[128];
struct Node* next;
};
// Adds to the front!
struct Node* add2front(char* val, struct Node* L);
// Recursive, prints it backwards!
void printList(struct Node* L);
// Deletes a list
void deleteList(struct Node* L);
int main()
{
struct Node* mylist = NULL;
char s[128];
while( scanf("%s", s) == 1 && strcmp(s, "END") != 0 )
mylist = add2front(s, mylist);
printList(mylist);
deleteList(mylist);
return 0;
}
|
// Adds to the front!
struct Node* add2front(char* val, struct Node* L)
{
struct Node* T = malloc(sizeof(struct Node));
strcpy(T->data, val); // ***NOTE HERE***
T->next = L;
return T;
}
// Recursive, prints it backwards!
void printList(struct Node* L)
{
if ( L != NULL )
{
printList(L->next);
printf("%s\n", L->data);
}
}
// Deletes a list
void deleteList(struct Node* L)
{
if( L != NULL )
{
deleteList(L->next);
free(L);
}
}
|
Mandatory Practice Problem
Write a program that reads in Mids.txt (41 lines) and
with alpha as input, prints out the name of the Midshipman.
Sample runs
$ ./a.out
Enter alpha: 185112
RAINEL NUNEZ
$ ./a.out
Enter alpha: 200000
No Mid with that alpha was found!
Solution