As a mathematician and advanced Java developer, I realized I never touched the C programming language. So yesterday, taking the benefit of a rainy day off, I decided to experiment it. See this text as friendly feedback!

So the genesis of this adventure was a disappointment around type inference in Java (must confess!), after which I thought: the more complicated the language, the least you can actually do.

Then I thought about very simple languages I knew (Cobol, SQL, and JS to be honest) and I told myself that those look like good languages if and only if the amount of code you have to manage is small, by code unit, mainly because of type safety. This made me think about Haskell and FP paradigm in general, where the basic moto is “write small pure functions only”.

Those rely on a strong type system, but other languages as JavaScript can also be fun to code in if we focus on small methods at a time. Then, not really knowing why, I thought about C.

Before I started the journey, I only knew that C had struct (which (nearly) exist in Java under record ) and pointers. Pointers do not really exist as such in Java, although everything stored in some Object-like variable should be thought off as such!

So I decided to give C a try, and I wanted to see how one could define the notion of Iterator.


The Java interface for an Iterator is pretty straightforward and looks like this (simplified):

interface Iterator<T> {
   /* Returns true if the iterator has a next element, false otherwise */
   boolean hasNext();
   /* Returns the next element, throws if no such element exists */
   T next();
}

Implementing this interface on the given of an array may look like this:

class IteratorOnArray<T> implements Iterator<T> {
   private final T[] array;
   private int counter = 0;

   IteratorOnArray(T[] array) { this.array = array; }
   @Override public
   boolean hasNext() {
      return counter < array.length;
   }
   @Override public
   T next() {
      return array[counter++];
   }
}

Java is a pretty straightforward language after all. So, what could be the equivalent of the above Java code, in C?

#learning #oop #c-language #java #programming

From Java to C
1.05 GEEK