The C Language

Posted by: Rea Maor In: Programming - Sunday, April 29th, 2007

C is pretty much the basis of all programming language today. Every language that we use today is either a derivative of C (C++, Objective C, C-99, C#), inspired by C (Java, PHP), or the interpreter or scripting engine for the language is written in C. Should you learn C? Almost definitely, if you want to program for a career. Even if you never use C or a derivative, you will still understand programming better than if you hadn’t.

A question that comes up is “Which should I learn first? C, C++, C#?” That is so much up to debate that we won’t answer it here. But all C languages have some original C syntax in them, so you won’t be hurting yourself to pick up C first, then branch to C++.

Like assembler, C is a compiled language. You can go two ways with this: either get a fancy IDE development kit that comes with a visual editor, compiler and library linker plus a lot of chrome and toys all built in one, or… use any old text editor and command-line compiler. Consider with a flashy software package, you’ll waste a lot of time learning the interface before you get down to learning the language. There is no reason that any language should require more than a plain old text editor (Notepad, Emacs, etc.) and a compiler to turn the code into an executable program or the interpreter to run it.

Some free C compilers:

  • Icc-win32 , Windows. Free for non-commercial use. A student learning C is non-commercial.
  • GCC , Unix. The standard compiler for all of GNU, Linux, BSD, Solaris, and just about everything besides Windows and Apple. Free to use for any purpose, including commercial. GCC is pretty much standard throughout the professional industry.
  • XCode , Mac/Apple. A port of gcc for Apple, free for download with membership. Many times, you will find that Unix software mixes better with Mac platforms than you might have thought. Mac OS is based on BSD, after all!
  • DJGPP , Windows/DOS. The gcc port to Windows. Free forever for anything.
  • Bloodshed software’s Dev-C++ , a fancy IDE for Windows/DOS. It can handle C as well as C++. Free download or buy a cheap disk with this and other programs. Not very difficult to learn, even for the beginner. I’ve heard Windows programmers swear by it.

Fast, here’s the basics of C:

Comments:


// comment line, or
/* Comment line .... or even */
/* #####################################
# #
# Comment box #
# #
##################################### */

So, comments either begin with a double / or are enclosed by /*… */.

Data declarations:


int score = 100;
float temperature = 97.2;
char date[24] = "January 1, 2000";
float prices[3] = { 19.99, 25.99, 0.99 };

Note the semi-colons at the end of the line! That’s how we tell C that this is one complete command. C is white-space indifferent, which means that you can run the whole thing on one line if you wanted to. C is not a dynamically typed language, which means you have to tell it whether the data you’re giving it is a number, a number with a decimal point, a string of characters, and so on.

Output statement:


printf("Press any key to continue...");
char message[100]="This is my string, there are many like it but this one is mine.";
printf("%s\n", message );

Printing plain old text. Of course, with the assistance of a library, our output could just as well be graphics or sound! “Printf” is the print function. The first example is a string literal, and the second uses a variable which it replaces %s with. The “\n” is the character code for a new line (remember assembly’s ’10’ code yesterday?)

Input statement:


fgets(str, 10, stdin);

A way for you to talk to the program! This statement uses the “fgets” function to read 10 bytes of input from the keyboard (stdin, standard input) and put it into the variable ‘str’. Other forms of reading input would be getting mouse clicks, or using a library function to read keyboard signals. For example, the ncurses library (a text-screen display system) would use “ch=getch()” to read a key press event into the variable “ch”.

Math:


x=x+y;
counter++;
winnings=score*bet;

Pretty straightforward. Other higher math functions would use functions; example: log(x/y); These can get hairy:


C=(C+(log((x/y)+(tan(x&y)/y))));

is an integral part of the code for a program I wrote years ago that draws fractal type patterns. I have no idea how. This is why comments are important!

File access:


fp=fopen("records.txt", "w");
fprintf(fp, "Sam Brown %d exempt from health plan", EID);

The top statement creates a file handler variable accessing “records.txt” in “w”rite mode. The bottom statement writes a line to that file.

Conditional statements:

The whole reason programs do something useful! This is integral to the process of software: not many programs would be useful if they just blindly executed a series of statements. They have to test a variable or condition and do one thing or another based on the result of that test. Here’s one way you do that:


if((strcmp(month, "May")) && (Time_of_Day == 12))
{
printf("It's Spring!\n");
}

“strcmp” is the string compare function. The parenthesis enclose two tests, one for the string and one to test the value of “Time_of_Day” Note the curly braces {} these are delimiters and tell the compiler that this block of code if to be executed only under the condition that the if statement is true.

Here’s another conditional form:


switch(balance)
{
case 100:
do_low();
break;
case 200:
do_medium();
break;
case 300:
do_high();
break;
default:
printf("Error in balance value\n");
exit(1);
break;
}

The above block is just short-hand for saying if(balance==100){do_low;}, etc.

Fixed iteration:

Another concept integral to program usefulness is to tell it to repeat commands a certain number of times. Here’s how you might blank a graphics array that is 640×480 pixels:


for(x=0;x<640;x++)
for(y=0;y<480;y++)
{
init_array("null");
put_pixel(x,y,0);
}

Note that this is two nested “for loops”. The for loop is another shorthand; we’re creating the variable (y=0), testing it for the maximum value (y<480), and telling it to add one to that value (y++) each time it executes until the maximum value condition is met (when (y==480)).

Conditional iteration:

A similar concept is iterating based on some other condition besides a counting variable.


while(signal != 37)
{
do_program();
}

The variable “signal” might be loaded with the value “37” when the user clicks the “X” close button at the top of the program’s window! Another example:


while(entry_code != 666)
{
printf("access denied!\n");
get_entry();
}

Hey, it’s a password loop!

Libraries:

C doesn’t come knowing this stuff out of the box. To use functions like “printf”, that function has to be predefined. This can be done in a separate file and then included, and the compiler’s pre-processor handles that when you tell it:


#include <stdio.h>

Which fetches the “header file” from your library. The compiler will also link your program against the library files required to execute the functions. You can also declare your own functions:

Functions:


int square_it(int x)
{
int z = x * x;
return z;
}
int main()
{
number = square_it(2);
...
exit(0);
}

The top block is the function you created. The bottom block is the “main” point of execution – all C programs have a “main” function. Just like assembly’s “_start” declaration, C doesn’t start executing anything until it sees the main() function.

Whew! As you can C, C is quite powerful and a sharp step up from assembler. Yet it is still fast enough to handle anything from a 3D game to a whole operating system. Please, forgive my slop code in here; you do not know C from reading this! This is just some example code to give you an idea what it looks like. But do familiarize yourself with the sections above; the syntax may change from one language to another, but you will be meeting these concepts again and again in almost every programming language you see.

Next post, we increment the experience with C++!

If you’ve enjoyed this post, consider subscribing to my blog feed for free updates


Related Posts:


Leave a Reply