introduction to c. topics covered creating a program in c editing, compiling, linking, running c...
Post on 31-Dec-2015
221 Views
Preview:
TRANSCRIPT
Introduction to C
Topics Covered Creating a program in C
editing, compiling, linking, running
C basics program structure, variables, statements
Conversion from pseudocode if, case, for, while, etc..
Functions
Creating a C Program
C source file
Texteditor
Object file
Compiler
Executablefile
Linker
Plain text (ASCII) file, human readable
Machine code, readable by computer
Final executable, contains code to load and run program
Externallibraries
Creating Source Files C source code is a simple text file Can be created in any text editor
notepad vi (simple Unix text editor) gedit, kate, etc, etc..
Has the extension .c .C, .cc, .cpp are for C++ .java for Java, etc..
C source code cannot be run directly, it must be compiled and linked first – converted into machine code, then combined into executable form
Compiling the C Source Code Compiling is the process of turning source code (human
readable) into machine code (machine readable) This is done by a compiler
the standard compiler is cc or gcc syntax: gcc myprogram.c
The output of the compiler is an object file is made up of machine code and symbol tables cannot be run directly, as it contains no loader, and libraries are
not yet linked If source code is incorrect in any way, the compiler will return
an error and terminate, or give a warning and continue
Linking to Create an Executable Object files must be linked before they can be run The linker performs the following tasks:
resolves external references to other libraries printing to screen, graphics, etc..
add operating specific code to load the program into memory Unix linker is ld
this is also a part of gcc, which by default links immediately after compiling! however they are still two separate processes use the –c flag to prevent linking
Linking can also produce errors external references not found in supplied libraries no ‘main’ program to load into memory
Default output filename is a.out (in Unix, in Windows a.exe) can be changed using the –o option of gcc
Running the Program Once successfully linked, the program is just
like any other executable file to run, simply enter the filename and path at the command
line./a.out./my_program
Unlike DOS and Windows, executable files in Unix do not end in .exe or .com can have any name, any extension executable status is indicated by permission bit ‘x’ coloured green where available in ls listing ls –l will show all permission bits in first column
Anatomy of a C Program A C source file consists of many parts
pre-processor directives comments
any section enclosed by /* */ any part of line following the // symbol
function declarations and bodies Every program must have one function called main
this is the PROGRAM module other functions can be declared to represent other modules in the
pseudocode C is case-sensitive
While != while, my_Program != my_program, etc.. C does not care about whitespace
tabs, spacing, newlines, etc, are meaningless, but still good programming practice!
Simple C Program#include <stdio.h>
/* HelloWorld program Author: Andrew Busch Date: 14/08/06*/
int main ( void ){printf ( “Hello World!\n" ) ; // another comment here
}
Another C Program#include <stdio.h>
/* Addnumbers program A simple program to add two numbers Author: Andrew Busch Date: 14/08/06*/
int main ( void ){
// variables are declared up here int num1, num2 ; int total ; // all the printf function from the stdio library printf ( "Please enter the first number\n" ) ; // now call scanf to read from the keyboard scanf ( "%d", &num1 ) ; printf ( "Now enter the second number\n" ) ; scanf ( "%d", &num2 ) ;
// now calculate the total
total = num1 + num2 ;
// and display it
printf ( "The total of %d and %d is %d\n", num1, num2, total ) ;
}
C Syntax C programs are comprised of functions
these are the equivalent of modules one function must be called ‘main’
A C function is defined by: its name the number and type of its inputs its return type
The body of the function is contained within braces { } this is the same as the pseudocode statements which
make up a module
C Function Example
int sum ( int num1, int num2 ){
// statements go here!
}
function name
return type
inputs (parameters, arguments)
C Functions Functions other than main should be declared
before they are used this means telling the compiler that they exist, even if you
have not written them yet, or they appear later in the file it is not strictly necessary, but if it is NOT done, the
compiler will make assumptions about these functions which may cause errors
Declaring a function is done by replacing the body in { } with a semicolon
int sum ( int num1, int num2 ) ;
C Statements A function is a collection of statements A statement can be:
a variable declaration an expression (including assignment) a conditional statement (if, case) a loop (for, while, do..while) a function call other special statements ( break, return, continue, etc..)
Combinations of the above are also possible eg, a function call is used within an expression
Each statement is terminated with a semicolon ; statements which have bodies (loops, conditionals) terminate when the
loop body finishes – after the closing { }
Variable Declarations Variables in C must be declared before than can be used Syntax:
type var_name [ = initial_value ] ; type can be any valid C data type var_name can contain letters, digits, and _
but cannot start with a number!! initial value is optional
Multiple variables of the same type can be declared in a single statement
int a ;int b = 10 ;double c, d = 15.23 ;
Variables Declarations Variables should be declared at the start of a function
this was historically mandatory modern compilers allow some flexibility
Variables inside the same function cannot have the same name but variables in different functions can these are still different variables!
Variables are only accessible within the function they are declared in
this is known as ‘scope’ the variable only exists while the function runs, then it is destroyed
Variables can be declared outside of any function ‘global’ variables – accessible to any function global variables live for the duration of the program – they are not
destroyed should be used sparingly, or not at all
Expressions Expressions range from very simple to extremely complex An expression (formally) is either:
a literal value a variable a function call (with any necessary paramters) an operator (with arguments)
arguments are also expressions! Clearly, expressions can be quite long! Examples:
3 ;a = b + 4 ;a = ( 4 < sqrt (7) ) ;printf ( “%f”, ( sin ( 17 – ( 5 / a % 13 )) + b / 4 ) / ( z + 3 – a == 13 )) ;
Operators in C Classified by the number of operands
unary – 1 operand binary – 2 operand trinary – 3 operand
Some operators have restrictions on what type of expressions each operand may be
eg, LHS of = operator must be a variable Classes of operators:
arithmetic: +, -, /, *, % assignment: = relational: <, <=, ==, >=, >, != logical: &&, ||, ! bit operators: ~, &, |, ^, <<, >> parentheses: (), [] special: *, ., &, ->, ?:
Operators All operators have a ‘result’ associated with them!
even those that don’t ‘make sense’ assignment (=), etc..
Some operators have side-effects as well, eg ‘=‘, ‘++’, ‘+=‘, etc.. Operators follow rules of precedence
(), [], ., -> L-R all unary operators R-L multiplicative L-R additive L-R bitshift L-R inequality L-R equality L-R bitwise logical
AND L-R XOR L-R OR L-R
logical (same order as above conditional L-R assignment R-L
Shortcut Arithmetic Operators Increment operators:
++ either before or after a value known as prefix or postfix increment operators both increase the variable by 1
postfix does this after returning the value prefix does this before returning the value
Examples: b = 10 ; a = b++ ; // a is assigned 10 a = ++b ; // a is assigned 11
Decrement operators (--) are the same for -1
Shortcut Operators Assignment can be integrated with most
arithmetic and logical operations operators are: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= variable is modified and overwritten with the result eg:
a += 15 ; // 15 is added to a b %= 4 ; // b is divided by 4, rem stored
// in b z <<= 2 ; // z is bit shifted two places left
Operator Examples What is performed by the following C
statements:int a, b, c, d = 4 ;
a = b = c = d + 10 ;
a += --b ;
c %= d ;
d = a + ( b = c <<= 1 ) ;
Logical and Relational Operators In C, FALSE is represented by 0
TRUE is equal to anything else The output of logical operators is 0 (FALSE) or 1 (TRUE)
7 || 0 equals 1 5 && 0 equals 0
Care must be taken not to mix = and ==, as they are both VALID, but have completely different meanings!if ( a = 10 ){ // this statement is ALWAYS TRUE!!
}
Input and Output in C C has no ‘built-in’ IO functions
they must be imported from a library the standard C IO library is <stdio.h> to use this library, put this line in the preprocessor block:
#include <stdio.h> The functions of most interest are:
printf writes formatted output to the screen scanf reads formatted input from the keyboard
‘Formatted’ means that you can specify how the output will be written or the input will be read as an integer, character, floating point number, string, etc..
printf Statement Syntax:
printf ( format_string, var1, var2, … ) ;
printf is somewhat unique in that it takes a varying number of parameters depending on the format string, zero or more variables are
also required The format string can be any string of text
it will be directly copied onto the screen the ‘%’ character however has a special meaning,
depending on the next character to follow it
printf Statement printf formatting characters:
%d, %i integer value %f, %g floating point value %c character %x, %X hexidecimal number %o octal number %s string
The behaviour of some formatting chars can be modified, eg: %lf, %lg is a long float, ie a double %.2g specifies 2 digits of precision after decimal point
The return value of printf is the number of characters written to the screen – this value is rarely used
Each time a formatting (%) character appears, it is replaced by the corresponding variable in the parameter list, by position
ie, the first % symbol is matched with the variable immediately following the format string printf will NOT perform checking to ensure the variables match, so be careful!
printf Statement Other characters in printf statements are ‘special’
escaped characters are preceded by a backspace some common examples are:
\n newline\r linefeed\t tab
others can be found with ‘man printf’ command in linux Examples of printf:
printf ( “Hello world\n” ) ;printf ( “The value of x is %i\n”, x ) ;printf ( “The average mark for CSE is %1.2g\n”, avg ) ;printf ( “%s is %d years old\n”, name, age ) ;
scanf Statement scanf is the input equivalent of printf The syntax is identical, ie
scanf ( format_string, var1, var2, … ) ; However, the address of the variable to store the input in
must be passed, not the variable itself this means, put a & in front of the variable name!
Eg, to read a single integer from the keyboard:int i ;scanf ( “%d”, &i ) ;
The return value of scanf is the number of items successfully read this should always be checked to ensure that the input was in
the correct format
Conditionals in C C has conditional statements equivalent to
the IF and CASE in pseudocode IF..THEN..ELSE = if..else CASE..IS = switch..case
The syntax of these statements is quite similar to their pseudocode equivalents
if Statements Syntax:
if ( expression )statement ;
elsestatement ;
The else part of this statement is optional By default, only the single statement forms part of the if statement
to overcome this, multiple statements are surrounded in braces { }if ( expression ){
statement1;statement2;
} else {statements…
} These if statements can be nested as in pseudocode
Common Errors with ‘if’ Forgetting the braces can have unexpected results:
if ( x < 10 )x++ ;printf ( “x is now %d\n”, x ) ;
The printf statement is executed regardless of the value of x! it is NOT part of the if statement, only the first statement is
Using a ‘=‘ instead of ‘==‘ can also have unexpected consequencesif ( x = 0 ){ // this is ALWAYS false and x is now 0!!
…}
switch Statements switch is the C equivalent to CASE Syntax:
switch ( expression ){case value1: statements ;
…break ;
case value2: statements ;…break ;
default: statements ;…break ;
} The ‘break’ statements are essential – without them execution will continue
into the next case block! As with pseudocode, the case values must be literals, they cannot be
variables!
Loops in C C has loops equivalent to each of those used in
pseudocode WHILE..DO = while REPEAT..UNTIL = do..while FOR..DO = for
The syntax for each is a little different Like conditionals, loops only process the next
single instruction by default this can be overcome by surrounding multiple statements
inside { }
while Loop Syntax:
while ( expression ){
statements…
}
expression is evaluated at the start of each iteration the loop continues while it evaluates as TRUE (!=0)
If the braces are omitted, only the very next statement is looped
do..while Loop Syntax:
do{
statements ;
} while ( expression ) ;
Identical to while loop, however expression is evaluated at the end of the loop guaranteed to loop at least once
Unlike REPEAT statement, continues while the expression evaluates to TRUE, not FALSE
for Loop Most complex C loop
very different syntax to pseudocode version Syntax:
for ( init_statement ; cont_expr ; incr_expr ){statements ;
} It works as follows:
init_statement is executed ONCE only, before the loop starts the first time cont_expr is executed before each loop, loop only continues if it evaluates to TRUE (same as while
loop) incr_expr is executed at the END of every loop
Typically: init_statement is used to initialise the loop variable cont_expr is used to specify the finishing value for the loop incr_expr is used to update the loop variables (increment or decrement)
However they can be used for anything, and can be empty!
for Loop Example This is typical example of a for loop
int i ;
for ( i = 0 ; i < 10 ; i++ ){
printf ( “%d\n”, i ) ;
}
This would print out the values 0..9 to the screen
Functions All program code in C must be contained within a function
body: the main function is the program block other functions are modules
Functions in C can have only one direct output this is the first type in the declaration, and does not have a
name as in pseudocode The output of a function is achieved using the return
statement:return ( value ) ; OR return value ;
This indicates that the given value is the output of the function, and immediately terminates the function!
Function Example
float par_resist ( float r1, float r2 ){
float total ;total = r1*r2 / ( r1 + r2 ) ;return ( total ) ;
}
return type arguments
return statement
Calling Functions Functions are called with the following syntax:
function_name ( arg1, arg2, arg3 ) ; Note that the types of the arguments are omitted If a function has NO arguments, you still need the ()! If the function returns a value, it can be assigned to a variable
or used in another expression. Consider the previous example..
int main ( void ){ float r1 = 123.25 ; float r2 = 2300 ; float total ;
total = par_resist ( r1, r2 ) ;}
top related