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:

Today we'll look at functions, and linked lists. The summary is actually pretty easy:

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


#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