2.2. Similarities to Java

Java has been called Smalltalk with C syntax. Because of that, if you know Java you already know some C.

Comments

/* This is a comment. */

Many C compilers will accept the // form of comment.

  // This is a comment.

Types

C primitive types are mostly the same as in Java. You can use types int, long and double.

Differences include

  1. Values of type char are one byte long. They can hold one-byte characters or integers. As integers, they are signed (from −128 to 127).

  2. There is no boolean type. But you can define your own type boolean and constants false and true as follows.

      typedef int boolean;
      #define false 0
      #define true  1
    

  3. Write unsigned in front of type int, long or char to treat numbers as nonnegative values.

Variables and assignment

Variables look similar to Java variables. For example,
  int x;
  x = 1;
creates variable x and stores 1 into it. Alternatively, you can create a variable and initialize it in one statement.
  int x = 1;

There is an important difference from Java. In C, you can only create variables at the beginning of a block {…}. You cannot create a variable after any statement that is not a variable-creation statement. So

 {
  int x;
  x = 1;
  int y;
 }
is not allowed. But
 {
  int x = 1;
  int y;
 }
is allowed.

Arithmetic operators

Arithmetic operators +, −, *, / and %, are the same as in Java.

Control structures

Control structures are mostly the same as in Java. There are if-statements, while-loops, do-loops, for-loops and switch-statements.

One difference has to do with conditions. In Java, a condition must have type boolean. In C, a condition can have any integer or pointer type. Number 0 is treated as false and anything except 0 is treated as true.

Another difference has to do with for-loops. In C, you cannot create a variable in a for-loop heading. For example,

  for(int i = 0; i < n; i++) 
  …
is not allowed. Just create the variable separately.

Functions

C functions are similar to Java methods. For example, here is a silly little function.
  int sum(int x, int y)
  {
    return x + y;
  }
Do not write private or public in front of a function heading.

C is peculiar about functions that take no parameters. Definition

  void sayHello()
  {
    printf("Hello\n");
  }
is allowed, but the empty set of parentheses tell the compiler that this function is unchecked. When you call it, the compiler will not check that the parameters are correct.

To define a function with no parameters, follow this example.

  void sayHello(void)
  {
    printf("Hello\n");
  }