Java has been called Smalltalk with C syntax. Because of that, if you know Java you already know some C.
Comments
Many C compilers will accept the // form of comment.
// This is a comment.
Types
Differences include
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).
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
Write unsigned in front of type int, long or char to treat numbers as nonnegative values.
Variables and assignment
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
Control structures
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
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"); }