Friday, 8 February 2013
Saturday, 2 February 2013
C Basics
Before we embark on a brief tour of C's basic syntax and structure we offer a brief history of C and consider the characteristics of the C language.
In the remainder of the Chapter we will look at the basic aspects of C programs such as C program structure, the declaration of variables, data types and operators. We will assume knowledge of a high level language, such as PASCAL.
It is our intention to provide a quick guide through similar C principles to most high level languages. Here the syntax may be slightly different but the concepts exactly the same.
C does have a few surprises:
- Many High level languages, like PASCAL, are highly disciplined and structured.
- However beware -- C is much more flexible and free-wheeling. This freedom gives C much more power that experienced users can employ. The above example below (mystery.c) illustrates how bad things could really get.
History of C
The milestones in C's development as a language are listed below:
- UNIX developed c. 1969 -- DEC PDP-7 Assembly Language
- BCPL -- a user friendly OS providing powerful development tools developed from BCPL. Assembler tedious long and error prone.
- A new language ``B'' a second attempt. c. 1970.
- A totally new language ``C'' a successor to ``B''. c. 1971
- By 1973 UNIX OS almost totally written in ``C''.
Characteristics of C
We briefly list some of C's characteristics that define the language and also have lead to its popularity as a programming language. Naturally we will be studying many of these aspects throughout the course.
- Small size
- Extensive use of function calls
- Loose typing -- unlike PASCAL
- Structured language
- Low level (BitWise) programming readily available
- Pointer implementation - extensive use of pointers for memory, array, structures and functions.
C has now become a widely used professional language for various reasons.
- It has high-level constructs.
- It can handle low-level activities.
- It produces efficient programs.
- It can be compiled on a variety of computers.
Its main drawback is that it has poor error detection which can make it off putting to the beginner. However diligence in this matter can pay off handsomely since having learned the rules of C we can break them. Not many languages allow this. This if done properly and carefully leads to the power of C programming.
As an extreme example the following C code (mystery.c) is actually legal C code.
#include <stdio.h>main(t,_,a)urn!0<t?char *a; {rett<3?main(-79,-13,a+main(-87,1-_,main(-86, 0, a+1 )+a)):1,t<_?main(t+1, _, a ):3,main ( -94, -27+t, a)&&t == 2 ?_<13 ?main ( 2, _+1, "%s %d %d\n" ):9:16:t<0?t<-72?main(_,t,"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+\+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# ){n\,/+#n+,/#;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l q#'+d'K#!/\ l]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#\/ ') }+}{rl#'{n' ')# }'+}##(!!/") :t<-50?_==*a ?putchar(a[31]):main(n'wk nw' iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \ ;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;\ #'rdq#w! nr '-65,_,a+1):main((*a == '/')+t,_,a\ +1 ):0<t?main ( 2, 2 , "%s"):*a=='/'||main(0,main(-61,*a, "!ek;dc \i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}
It will compile and run and produce meaningful output. Try this program out. Try to compile and run it yourself. Alternatively you may run it from here and see the output.
Clearly nobody ever writes code like or at least should never. This piece of code actually one an international Obfuscated C Code Contest http://reality.sgi.com/csp/iocc The standard for C programs was originally the features set by Brian Kernighan. In order to make the language more internationally acceptable, an international standard was developed, ANSI C (American National Standards Institute).
C Program Structure
A C program basically has the following form:
- Preprocessor Commands
- Type definitions
- Function prototypes -- declare function types and variables passed to function.
- Variables
- Functions
We must have a main() function.
A function has the form:
type function_name (parameters){local variablesC Statements}
If the type definition is omitted C assumes that function returns an integer type. NOTE: This can be a source of problems in a program.
So returning to our first C program:
/* Sample program */main() {e Cprintf( ``I Li kn'' );
exit ( 0 );}
NOTE:
- C requires a semicolon at the end of every statement.
- printf is a standard C function -- called from main.
n signifies newline. Formatted output -- more later.
- exit() is also a standard function that causes the program to terminate. Strictly speaking it is not needed here as it is the last line of main() and the program will terminate anyway.
Let us look at another printing statement:
printf(``.
n.1
n..2
n...3
n'');
The output of this would be:
.1.....2.3
Variables
C has the following simple data types:
The Pascal Equivalents are:
On UNIX systems all ints are long ints unless specified as short int explicitly.
NOTE: There is NO Boolean type in C -- you should use char, int or (better) unsigned char.
Unsigned can be used with all char and int types.
To declare a variable in C, do:
var_type list variables;
e.g. int i,j,k;float x,y,z;char ch;
Defining Global Variables
Global variables are defined above main() in the following way:-
short number,sum;int bignumber,bigsum;() {char letter; main }
It is also possible to pre-initialise global variables using the = operator for assignment.
NOTE: The = operator is the same as := is Pascal.
For example:-
float sum=0.0;int bigsum=0;'; main()char letter=` A {}
This is the same as:-
float sum;int bigsum;main()char letter ; { sum=0.0;tter=`A';big
Subscribe to:
Posts (Atom)