C for Java Programmers




CS152

Chris Pollett

Feb. 4, 2009

Outline

Introduction to C and Unix Environment

Unix Environment Remarks

More Unix

For those of you unfamiliar with Unix we next look at some of the most important shell concepts/commands to get started with:

Still more Unix

A Basic C Program: hello.c

#include <stdio.h> //for printf statement
int main()
{
   printf("Hello World\n");
   return 0;
}

To compile and run this program:

gcc hello.c -o hello
./hello 

Remarks on hello.c

Similarities b/w Java and C

Important differences

You don't have a class construct. You can pretend --if it helps -- as if everything is declared in the same class. Although, these rules were relaxed somewhat in C99 from ANSI C, you should have all your variable declarations at the start of your functions:

void foo()
{
	int a=1;
    printf("%d", a);
    int b; // ANSI C's head explodes
}

Similarly, you either need to have a function prototype, or the function itself before the first place you use it -- See next slide.

Function examples

//the following is okay:
char foo();
void bar()
{
     printf("%c", foo());
}
char foo( )
{
     return 'a';
}

Program structure

Generally, for each module (say .c file) of your program, you put all its function prototypes, struct definitions, #define's, global variable declarations, etc. into a header file (a .h file) for that program and then include it with the line like:

#include "foo.h" /* double quotes unlike <foo.h>, also searches current directory */

Since, you might use the same header file for several modules, the header file might have at its start some preprocessor code like:

#ifndef FOO_H
#define FOO_H
//header file code
#endif // this prevents the header from being included more than once.

Pointers

Roughly, pointers allow us to refer to a memory address.

Example:

 
   int a, *b; /* b is declared as a pointer to an int memory address */
   a = 5;
   b = &a; /* now b points at where a is stored in memory */
   printf("%d", *b); //prints 5.
   *b = 6; /* this changes the value of what's stored at the address b points to */
   printf("%d", a); // prints 6.

More Pointers