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. For instance:

struct Mid {
  char* name;        
  int alpha;      
  int OOM;
};

void readMid(struct Mid m) {
  // do stuff    
}
  
int main() {    
    // Create a variable of type Mid
    struct Mid a;

    // do stuff...
}

Wherever you put Mid now needs to be struct Mid. You can probably now see why the C++ designers wanted to get rid of that.

Linked Lists

Fundamentally, there is no real difference between C and C++.

struct Node* add2front(int val, struct Node* L) {
  struct Node* T = malloc(sizeof(struct Node));  // get the size of a Node struct!
  T->data = val;
  T->next = L;
  return T;
}

I'm including C code to read a linked list from the user (stop at -1) and print it:


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

struct Node {
  int data;
  struct Node *next;
};

// Adds to the front!        
struct Node* add2front(int val, struct Node* L) { 
  struct Node* T = malloc(sizeof(struct Node));
  T->data = val;
  T->next = L;
  return T;
}

// Recursive, prints it backwards!
// Since the list is built backwards, this prints forward!              
void printList(struct Node* L) {  
  if( L == NULL )
    printf("\n");
  else {
    printList(L->next);
    printf("%d ", L->data);
  }
}

int main() {
  struct Node* mylist = NULL;
  int num;

  printf("Numbers? ");
  scanf("%d", &num);
  while( num != -1 ) {
    mylist = add2front(num, mylist);
    scanf("%d", &num);
  }

  printList(mylist);

  return 0;  
}

Problems

  1. A few weeks ago we had a C++ program that read student grades from a text file and averaged their grades. Take the C++ code and convert it to working C code that produces the same output.
    $ ./avg
    Enter name: Needham
    Average is: 71.1000005