C2scala

Introduction

There are a number of on-line sources which compare different high level languages with each other. However, I couldn't find a ready reference comparing C with a high-level language like Scala. I hope such a comparison will be useful for those who have to decide between C or a high-level language.

Overarching differences

There are many fundamental language differences between C and Scala and they are covered here. Specific use cases will be covered later along with code examples.

Object oriented

To wrap it in a nutshell, Scala is object-oriented while C is not.

Type inference

C requires you to specify the type of every expression.

// get a list of integers and 
// add first two elements of the list
int addTwo (void) {
  struct headNode *p = getList();
  return p->data + p->next->data;
}

Scala, in a number of cases, automatically infers the type of an expression.

// get a list of integers and
// add first two elements of the list
def addTwo = {
  val l = getList
  l(0) + l(1)
}

Memory management

C requires the programmer to manage memory manually; he should remember where memory was allocated, whether it is alive at the point of use and whether it gets freed when not used any more.

Scala uses garbage collection (memory management is done automatically). Generally speaking, this incurs a run-time penalty (both in time and space), but makes the programmer's life easy.

Higher order functions

Higher order functions are those functions that can take as input other functions and also can return functions.

You can get a limited form of Higher order functions using function pointers. Recent versions of gcc do support anonymous functions in a limited form. The most important limitation is that you can't define closures. More about Closures

Scala supports higher order functions, anonymous functions and closures. Functions are first-class values.

Specific use-cases

String operations

String concatenation

Let's say we have two strings, s1 and s2, and we want to create a new string that contains s1, " : " , s2.

For eg, if s1 = "hello" and s2 = "world", we want to get "hello : world"

In C,

char *myFunc(char *s1, char *s2) {
  char *s3 = malloc(strlen(s1) + strlen(s2)) + 3 + 1;
  strcat(s3, s1);
  strcat(s3, " : ")
  strcat(s3, s2);
  return s3;
}

Another way,

char *myFunc(char *s1, char *s2) {
  char *s3 = malloc(strlen(s1) + strlen(s2)) + 3 + 1;
  return strcat(strcat(strcat(s3, s1), " : "), s2);
}

Alternatively,

char *myFunc(char *s1, char *s2) {
  char *s3 = malloc(strlen(s1) + strlen(s2)) + 3 + 1;
  sprintf(s3, "%s : %s", s1, s2);
  return s3;
}

In Scala,

def myFunc(s1:String, s2:String) = s1 + " : " + s2