c Language
May 11, 2017 | Author: ashok | Category: N/A
Short Description
Download c Language...
Description
C Introduction & History
Birth of C •C is very often referred as a “System Programming Language” because it is used for writing compilers, editors and even operating systems. C was developed and implemented on the UNIX operating system on the DEC PDP-11, by Dennis M. Ritchie. •C was evolved during 1971-73 from B language of Ken Thompson, which was evolved (in 196970) from BCPL language of Martin Richards. “Every good tree produces good fruit.”
Programming Languages Phylogeny Fortran (1954) Algol (1958) LISP (1957)
Scheme (1975)
CPL (1963), U Cambridge Combined Programming Language Simula (1967) BCPL (1967), MIT Basic Combined Programming Language B (1969), Bell Labs C (1970), Bell Labs C++ (1983), Bell Labs
Java (1995), Sun
Objective C
Strengths
Low-level nature makes it very efficient
Language itself is very readable
Many compilers available for a wide range of machines and platforms Standardization improves portability of code Efficient in terms of coding effort needed for a wide variety of programming applications
Weakness
Parts of syntax could be better
if ( i = 1 )
is probably error, should be
if ( i == 1 )
stmt ...
stmt ...
Low-level nature makes it easy to get into trouble _ infinite loops
Weakness
Illegal memory accesses / tromping over memory Obfuscated code can be written main(n,i,a,m)
{
}
while(i=++n)for(a=0;a 0) || ( (y-x) >= < ~ Reference/Dereference: & *
Type conversions
Some types can automatically be converted to others int, float, double can often be treated the same for calculation purposes
int values will be converted up into floats for calc.
But major differences between integer and floatingpoint arithmetic!
Fractions just dropped in integer arithmetic Use mod (%) operator to get remainders Integer much faster to perform
Start here
Hello, World – a first program Hello, World – line by line Basic rules for C Tips for good programming style Basic Input/Output
Hello, World /* Hello, World program */ #include int main() { printf(“Hello, World!\n”); return 0; }
Programming Style
Put brackets on separate lines by themselves (some variations on this) After each open bracket, increase indentation level by one tab After each close bracket, decrease indentation level by one tab Leave blank lines between sections Don’t let lines get too long
Control Flow
Two basic types of control flow commands Conditionals
Execute some commands if a given condition is true/false if, switch, ?: operator
Loops
Execute some commands repeatedly until a given condition for stopping is met while, for, do-while
Functions
Basic idea of functions is to divide code up into small, manageable chunks One way to get started designing funcs:
Write out the entire program with no functions Look for sections of code that are almost exactly duplicated Create one function for each repeated section and replace each repetition with the function call
Function Design
Look for places where several lines of code are used to accomplish a single task and move the code into a function No function too small Rule of thumb: no function (including main) should be longer than a page
Goal: be able to see entire function at once when editing program
So,What is a function?
Types of function
Std UDF
Nature of function
Stack use Recursive Chained …
Using variable number of arguments •Macros that implement variable argument lists • Declaration: void va_start(va_list ap, lastfix); type va_arg(va_list ap, type); void va_end(va_list ap); • Remarks: •Some C functions, such as vfprintf and vprintf, take variable argument lists in addition to taking a number of fixed (known) parameters. •The va_arg, va_end, and va_start macros provide a portable way to access these argument lists. •va_start sets ap to point to the first of the variable arguments being passed to the function. •va_arg expands to an expression that has the same type and value as the next argument being passed (one of the variable arguments). Because of default promotions, you can't use char, unsigned char, or float types with va_arg.va_end helps the called function perform a normal return.
Using variable number of arguments… • ap •Points to the va_list variable argument list being passed to the function. The ap to va_arg should be the same ap that va_start initialized. • lastfix •The name of the last fixed parameter being passed to the called function. • type •Used by va_arg to perform the dereference and to locate the following item.
•You use these macros to step through a list of arguments when the called function does not know the number and types of the arguments being passed.
Using variable number of arguments… • Calling Order •va_start must be used before the first call to va_arg or va_end. •va_end should be called after va_arg has read all the arguments. •Failure to do so might cause strange, undefined behavior in your program.
•Stepping Through the Argument List •The first time va_arg is used, it returns the first argument in the list. •Each successive time va_arg is used, it returns the next argument in the list. •It does this by first dereferencing ap, then incrementing ap to point to the next item.
Using variable number of arguments… void sum(char *msg, ...) { int total = 0;
va_list ap;
int arg;
va_start(ap, msg); while ((arg = va_arg(ap,int)) != 0) { total += arg;} printf(msg, total); va_end(ap); } int main(void) { sum("The total of 1+2+3+4 is %d\n", 1,2,3,4,0); return 0; }
Arrays
An array variable is just a set of variables all of the same type, all linked together Can make an array variable of ANY type – built-in ones, or ones that you define with struct or enum char string[100]; // 100 chars int numArray[50]; // 50 ints Date dateArray[10]; // 10 Dates
Array Elements
Each element of the array can be treated like an individual object of the underlying array type To access an element, use the subscript operator: [] : represents the element at position in the array named
Array Indices
Indices into an array start at 0 and go up to (array length – 1). Very convenient when combined with for loops Can easily go through entire array to access every element in just a few lines of code, no matter how large the array
Example – with arrays #define ARRAYSIZE 10 int main() { int numArray[ARRAYSIZE]; int sum=0, i; for (i=0; i < ARRAYSIZE; i++) { numArray[i] = i; sum += numArray[i]; printf(“%d “, numArray[i]); } printf(“\nSum is: %d\n”, sum); return 0; }
Limitations
Can’t assign or compare arrays
int numArray[10]; int numArrayCopy[10]; // Not OK: numArrayCopy = numArray; if (numArray == numArrayCopy) // OK: for(I=0; I int x = 5+3;
Macros
Can make extremely complex macros Faster to execute than a function Much harder to debug than functions Example:
#define ADD(a,b) a+b int x = ADD(5,3)*2; =>int x = 5+3*2; Result: 5+6=11 NOT 8*2=16 #define ADD(a,b) ((a)+(b)) must be used
Macros
Macro definitions must all be on one line Can get long and messy Use \ at very end of line to continue it onto the next line #define COMPLEX_MACRO(a,b) \ printf(“complex macro\n”); \ printf(“%d+%d=%d\n”, \ (a),(b),((a)+(b)));
Conditional Compilation
Several conditional statements present in the preprocessor language Used to block out (or activate) chunks of code based on a single constant value Syntax: #ifdef /* conditional code goes here*/ #endif
Conditional Compilation Useful for debugging #define DEBUG #ifdef DEBUG printf(“Debugging info\n”); for (int i=0; i
View more...
Comments