Upload
judith-lane
View
223
Download
0
Embed Size (px)
Citation preview
Writing C Programs The programmer uses a text editor to
create or modify files containing C code.
C code is also called source code
A file containing source code is called a source file
After a source file has been created, the programmer must invoke the C compiler.
The Result : a.out
If there are no errors in pgm.c, this command produces an executable file, one that can be run or executed.Both the cc and the gcc compilers name the
executable file a.outTo execute the program, type ./a.out at the
Unix prompt. Although we call this “compiling a program”,
what actually happens is more complicated.
3 Stages of Compilation
1 Preprocessor - modifies the source codeHandles preprocessor directives
Strips comments and whitespace from the code
3 Stages of Compilation
2 Compiler - translates the modified source code into object codeParser - checks for errors
Code Generator - makes the object code
Optimizer - may change the code to be more efficient
3 Stages of Compilation
3 Linker - combines the object code of our program with other object code to produce the executable file.
The other object code can come from:The Run-Time Library - a collection of object
code with an index so that the linker can find the appropriate code.
other object filesother libraries
Compilation Diagram
Editor
Compiler Preprocessor
ParserCode Generator Optimizer
Linker
<
Source File myprog.c
Object File myprog.oOther Obj’s Run-time library Other libraries
Executable file a.out
An algorithm for writing code
Write the algorithm Write the code using vi (pico, emacs) Try to compile the code While there are still syntax errors Fix errors Try to compile the code Test the program Fix any semantic errors Compile the code Test the program
Incremental Approach to Writing Code
Tips about writing code. Write your code in incomplete but working
pieces. For instance: For your project
Don’t write the whole program at once.Just write enough that you display the prompt to
the user on the screen.Get that part working first.Next write the part that gets the value from the
user, and then just print it out.
Incremental Approach to Writing Code (continued)
Get that working. Next change the code so that you use the
value in a calculation and print out the answer.
Get that working. Make program modifications:
○ perhaps additional instructions to the user○ a displayed program description for the user○ add more comments.
Get the final version working.
Structure of a ‘C’ program
pre-processor directives
global declarations
function prototypes
main()
{
local variables to function main ;
statements associated with function main ;
}
f1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
f2()
{
local variables to function f2 ;
statements associated with function 2 ;
}.
A Simple C Program
/* Filename: hello.c Author: Brian Kernighan & Dennis Ritchie Date written: ?/?/1978 Description: This program prints the greeting
“Hello, World!” */
#include <stdio.h>
main ( ) { printf (“Hello, World!\n”) ; }
The Program Header Comment
All comments must begin with the characters /* and end with the characters */
The program header comment always comes first
The program header comment should include the filename, author, date written and a description of the program
Preprocessor Directive
Lines that begin with a # are called preprocessor directives
The #include <stdio.h> directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code.
This header file was included because it contains information about the printf ( ) function that’s used in this program.
main ( )
Every program has a function called main, where execution begins
The parenthesis following main indicate to the compiler that it is a function.
Left Brace
A left curly brace -- { -- begins the body of every function. A corresponding right curly brace must end the function.
The style is to place these braces on separate lines in column 1.
printf (“Hello, World!\n”) ; This is the function printf ( ) being called
with a single argument, namely the string “Hello, World!\n”
Even though a string may contain many characters, the string itself should be thought of as a single quantity.
Notice that this line ends with a semicolon. All statements in C end with a semicolon.
Right Brace
This right curly brace -- } --matches the left curly brace above.
It ends the function main ( ).
Common variable types
• int - stores integers (-32767 to +32768)
• unsigned int – 0 to 65535
• char – holds 1 byte of data (-127 to 128)
• unsigned char – holds 1 byte (0 to +255)
• long – usually double int (signed)
• unsigned long – positive double int
• float – floating point variable
• double – twice of a floating point variable
• Note: local, global and static variables
scanf
scanf (“conversion specifier”,variable);
scanf (“%d”,&i);
Usual variable type Display:
%c char single character
%d (%i) int signed integer
%f float or double signed decimal
printf
printf (“%d”,i);
Usual variable type Display
%c char single character
%d int
%i signed integer
%e (%E) float or double exponential format
%f float or double signed decimal
%g (%G) float or double use %f or %e as required
%o int unsigned octal value
%p pointer address stored in pointer
%s array of char sequence of characters
%u int unsigned decimal
%x (%X) int unsigned hex value
Operators
+ addition- subtraction* multiplication/ division% mod or remainder (e.g., 2%3 is 2), also called 'modulo'<< left-shift (e.g., i<<j is i shifted to the left by j bits)>> right-shift& bitwise AND| bitwise OR^ bitwise exclusive-OR&& logical AND (returns 1 if both operands are non-zero; else 0)|| logical OR (returns 1 if either operand is non-zero; else 0)< less than (e.g., i<j returns 1 if i is less than j)> greater than<= less than or equal>= greater than or equal== equals!= does not equal
Operators (contd.)
Increment and Decrement Operators
• ++ Increment operator
• -- Decrement Operator
• k++ or k-- (Post-increment/decrement)
k = 5;
x = k++; // sets x to 5, then increments k to 6
• ++k or --k (Pre-increment/decrement)
k = 5;
x = ++k; // increments k to 6 and then sets x to the
// resulting value, i.e., to 6
Example – total cost calculator
#include <stdio.h>
main()
{
float cost =0.0;
float tax = 0.08;
float totalCost = 0.0;
printf(“Enter the cost of the item:”);
scanf(“%f”, &cost);
totalCost = cost *tax + cost;
printf(“Total cost is : %f\n”, totalCost);
}
Functions and Prototypes
• Building blocks of code
• Group relevant and repetitive actions into
functions
• Variables are usually local (they exist only inside the function)
type FunctionName(type declared parameter list)
{
statements that make up the function
}
Example function
#include <stdio.h>
int add1(int);
void main()
{
int x;
x=5;
x=add1(x);
printf("%d“,x);
}
int add1(int i)
{
int y;
y=i+1;
return (y);
}
Returns an integer result
Expects an integer parameter
Conditional clauses
if (expression) statement
else statement
if (x==1)
{
printf(“Hello”);
printf (“hi\n”);
}
else
{
printf(“World’);
}
Unconditional Loops
for( initialization; expression; increment )
statement
for (i=0;i<100;i++)
{
printf("Hi.");
}
The switch statement
The C switch allows multiple choice of a selection of items
at one level of a conditional where it is a far neater way
of writing multiple if statements
switch (expression)
{ case item1:
statement1;
break;
case item2:
statement2;
break;
case itemn:
statementn;
break;
default:
statement;
break;
}
Pointers
• A pointer in C is the address of something
• The unary operator `&' is used to produce
the address of an object
int a, *b, c; // b is a pointer
b = &a; // Store in b the address of a
c = *b; // Store in c the value at
// address b (i.e., a)
• Pointers to pointers
• Pointers to functions
Character Pointers & Arrays
char *y;
char x[100];
y = &x[0];
y = x; // Does the same as the line above
*(y+1) gives x[1]
*(y+i) gives x[i]
Structures
• User defined ‘data type’
struct emprec
{
char name[25];
int age;
int pay;
};
struct emprec employee;
employee.age=32;
Nice to have
• Add plenty of comments /* */ or //
• Good layout.
main(){printf("Hello World\n");}
• Use meaningful variable names
• Use brackets to avoid confusion
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0
• Initialize your variables
Good Programming Practices
C programming standards are available on the Web
These standards include:Naming conventionsUse of whitespaceUse of BracesComments
Examples of Comment Styles /* a comment */ /*** another comment ***/ /*****/ /*A comment can be written in this * fashion to set it off from the * surrounding code. */
More Comments
/*******************************************\ * If you wish, you can put comments * * in a box. This is typically used for * * program header comments and for * * function header comments * \*******************************************/
Use of Whitespace
Use blank lines to separate major parts of a source file or function
Separate declarations from executable statements with a blank line
Preprocessor directives, main(), and the braces are in column 1
Use of Whitespace(continued)
All executable statements are indented one tab stop. How deep should my tabs be ?
Either 3 or 4 spaces. Choose whichever you like and use that same number consistently throughout your program.
2 spaces are not enough for good readability, more than 4 causes the indentation to be too deep.