




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
c program - c program
Typology: Lecture notes
1 / 112
This page cannot be seen from the preview
Don't miss anything!
6th Revision - lunedì giugno 29, 2015
F 0
1.2 The “Hello World” Program
A C program consists of one or more functions or code modules. These are essentially groups of instructions that are to be executed as a unit in a given order and that can be referenced by a unique name. Each C program must contain a main() function. This is the first function called when the program starts to run. Note that while "main" is not a C keyword and hence not reserved it should be used only in this context.
A C program is traditionally arranged in the following order but not strictly as a rule.
Function prototypes and global data declarations The main() function Function definitions
Consider first a simple C program which simply prints a line of text to the computer screen. This is traditionally the first C program you will see and is commonly called the “Hello World” program for obvious reasons.
#include <stdio.h>
void main() { /* This is how comments are implemented in C to comment out a block of text */ // or like this for a single line comment
printf( "Hello World\n" ) ;
As you can see this program consists of just one function the mandatory main function. The parentheses, ( ), after the word main indicate a function while the curly braces, { }, are used to denote a block of code -- in this case the sequence of instructions that make up the function.
Comments are contained within a /* ... */ pair in the case of a block comment or a double forward slash, //, may be used to comment out the remains of a single line of test.
The line printf("Hello World\n " ) ;
is the only C statement in the program and must be terminated by a semi-colon. The statement calls a function called printf which causes its argument, the string of
text within the quotation marks, to be printed to the screen. The characters \n are not printed as these characters are interpreted as special characters by the printf function in this case printing out a newline on the screen. These characters are called escape sequences in C and cause special actions to occur and are preceded always by the backslash character, .
All C compiler include a library of standard C functions such as printf which allow the programmer to carry out routine tasks such as I/O, maths operations, etc. but which are not part of the C language, the compiled C code merely being provided with the compiler in a standard form.
Header files must be included which contain prototypes for the standard library functions and declarations for the various variables or constants needed. These are normally denoted by a .h extension and are processed automatically by a program called the Preprocessor prior to the actual compilation of the C program.
The line #include <stdio.h>
instructs the preprocessor to include the file stdio.h into the program before compilation so that the definitions for the standard input/output functions including printf will be present for the compiler. The angle braces denote that the compiler should look in the default “INCLUDE” directory for this file. A pair of double quotes indicate that the compiler should search in the specified path e.g.
#include “d:\myfile.h”
NB : C is case sensitive i.e. printf() and Printf() would be regarded as two different functions.
1.3 The C Programming Environment
Program development is nowadays carried out in specifically designed software systems or workbenches with editing, compilation, linking, debugging and execution facilities built in. In this course we will be making use of a Microsoft system but the features found in this are to be found in one form or another in almost all modern systems.
The first phase of development involves the creation and editing of a file containing the appropriate C instructions which will be stored using a file extension of .c normally to invoke the C compiler, e.g. fname.c.
The next step is to take the C program and to compile it into object code or machine language code. The C compiler includes the aforementioned preprocessor which is called automatically before the code translation takes place. This preprocessor acts on special commands or directives from the programmer to manipulate the text of the C code before compilation commences. These directives might involve including other source files in the file to be compiled, replacing special symbols with specific replacement text, etc. Once this is done the C code is translated into object code and stored in a file with the extension .obj , e.g. fname.obj.
The final phase in building the executable program is called linking. After the compilation stage the C code has been translated into machine recognisable code but is in a somewhat unconnected state. The program invariably contains references to standard library functions or functions contained in other libraries or modules which must be connected to the C program at link time. This simply involves linking the machine code for these functions with the program’s object code to complete the build process and produce an executable file with an extension .exe e.g. fname.exe.
The executable program can be loaded and run from within the programming environment itself or may be run from the host environment directly. If it executes as expected that is the end of the task. However if this does not happen it may require the use of the debugger to isolate any logical problems. The debugger allows us to step through the code instruction by instruction or up to predefined break-points and to look at the values of variables in the code in order to establish where errors are introduced.
NB : Note that the keyword int may be omitted without error so that the type unsigned is the same as type unsigned int , the type long is equivalent to the type long int, and the type short is equivalent to the type short int.
2.2 Variables
A variable is a named piece of memory which is used to hold a value which may be modified by the program. A variable thus has three attributes that are of interest to us : its type, its value and its address.
The variable’s type informs us what type and range of values it can represent and how much memory is used to store that value. The variable’s address informs us where in memory the variable is located (which will become increasingly important when we discuss pointers later on).
All C variables must be declared as follows :- type variable-list ; For Example :- int i ; char a, b, ch ;
Variables are declared in three general areas in a C program.
When declared inside functions as follows they are termed local variables and are visible (or accessible) within the function ( or code block ) only.
void main() { int i, j ; ... }
A local variable is created i.e. allocated memory for storage upon entry into the code block in which it is declared and is destroyed i.e. its memory is released on exit. This means that values cannot be stored in these variables for use in any subsequent calls to the function.
When declared outside functions they are termed global variables and are visible throughout the file or have file scope. These variables are created at program start-up and can be used for the lifetime of the program.
int i ; void main() { ... } When declared within the braces of a function they are termed the formal parameters of the function as we will see later on.
int func1( int a, char b ) ;
Variable Names
Names of variables and functions in C are called identifiers and are case sensitive. The first character of an identifier must be either a letter or an underscore while the remaining characters may be letters, numbers, or underscores. Identifiers in C can be up to 31 characters in length.
Initialising Variables
When variables are declared in a program it just means that an appropriate amount of memory is allocated to them for their exclusive use. This memory however is not initialised to zero or to any other value automatically and so will contain random values unless specifically initialised before use.
Syntax :- type var-name = constant ;
For Example :- char ch = 'a' ; double d = 12.2323 ; int i, j = 20 ; /* note in this case i is not initialised */
Storage Classes
There are four storage class modifiers used in C which determine an identifier’s storage duration and scope. auto static register extern
An identifier’s storage duration is the period during which that identifier exists in memory. Some identifiers exist for a short time only, some are repeatedly created and destroyed and some exist for the entire duration of the program. An identifier’s scope specifies what sections of code it is accessible from.
The auto storage class is implicitly the default storage class used and simply specifies a normal local variable which is visible within its own code block only and which is created and destroyed automatically upon entry and exit respectively from the code block. The register storage class also specifies a normal local variable but it also requests that the compiler store a variable so that it may be accessed as quickly as possible, possibly from a CPU register. The static storage class causes a local variable to become permanent within its own code block i.e. it retains its memory space and hence its value between function calls.
When applied to global variables the static modifier causes them to be visible only within the physical source file that contains them i.e. to have file scope. Whereas the extern modifier which is the implicit default for global variables enables them to be accessed in more than one source file. For example in the case where there are two C source code files to be compiled together to give one executable and where one specific global variable needs to be used by both the extern class allows the programmer to inform the compiler of the existence of this global variable in both files.
2.3 Console Input / Output
This section introduces some of the more common input and output functions provided in the C standard library.
printf()
The printf() function is used for formatted output and uses a control string which is made up of a series of format specifiers to govern how it prints out the values of the variables or constants required. The more common format specifiers are given below
%c character %f floating point %d signed integer %lf double floating point %i signed integer %e exponential notation %u unsigned integer %s string %ld signed long %x unsigned hexadecimal %lu unsigned long %o unsigned octal %% prints a % sign
For Example :- int i ;
printf( "%d", i ) ;
The printf() function takes a variable number of arguments. In the above example two arguments are required, the format string and the variable i. The value of i is substituted for the format specifier %d which simply specifies how the value is to be displayed, in this case as a signed integer.
Some further examples :-
int i = 10, j = 20 ; char ch = 'a' ; double f = 23421.2345 ;
printf( "%d + %d", i, j ) ; /* values are substituted from the variable list in order as required */ printf( "%c", ch ) ;
printf( "%s", "Hello World\n" ) ;
printf( "The value of f is : %lf", f ) ;/*Output as : 23421. / printf( "f in exponential form : %e", f ) ; / Output as : 2.34212345e+
Field Width Specifiers
Field width specifiers are used in the control string to format the numbers or characters output appropriately.
Syntax :- %[total width printed][.decimal places printed]format specifier
where square braces indicate optional arguments.
For Example :- int i = 15 ; float f = 13.3576 ; printf( "%3d", i ) ; /* prints "_15 " where _ indicates a space character / printf( "%6.2f", f ) ; / prints "_13.36" which has a total width of 6 and displays 2 decimal places / printf( “%.f”, 6,2,f ) ; / prints "_13.36" as above. Here
There are also a number of flags that can be used in conjunction with field width specifiers to modify the output format. These are placed directly after the % sign. A - (minus sign) causes the output to be left-justified within the specified field, a + (plus sign) displays a plus sign preceding positive values and a minus preceding negative values, and a 0 (zero) causes a field to be padded using zeros rather than space characters.
scanf()
This function is similar to the printf function except that it is used for formatted input. The format specifiers have the same meaning as for printf() and the space character or the newline character are normally used as delimiters between different inputs.
For Example :- int i, d ; char c ; float f ;
scanf( "%d", &i ) ;
scanf( "%d %c %f", &d, &c, &f ) ; /* e.g. type "10_x_1.234 ret " */
scanf( "%d:%c", &i, &c ) ; /* e.g. type "10:x ret " */
The & character is the address of operator in C, it returns the address in memory of the variable it acts on. (Aside : This is because C functions are nominally call--by--value. Thus in order to change the value of a calling parameter we must tell the function exactly where the variable resides in memory and so allow the function to alter it directly rather than to uselessly alter a copy of it. )
Note that while the space and newline characters are normally used as delimiters between input fields the actual delimiters specified in the format string of the scanf statement must be reproduced at the keyboard faithfully as in the case of the last sample call. If this is not done the program can produce somewhat erratic results!
The scanf function has a return value which represents the number of fields it was able to convert successfully.
For Example :- num = scanf( “%c %d”, &ch, &i );
This scanf call requires two fields, a character and an integer, to be read in so the value placed in num after the call should be 2 if this was successful. However if the input was “a bc” then the
These functions perform the same operation as getchar() except that they are unbuffered input functions i.e. it is not necessary to type ret to cause the values to be read into the program they are read in immediately the key is pressed. getche() echoes the character hit to the screen while getch() does not.
For example :- char ch ; ch = getch() ;
2.4 Operators
One of the most important features of C is that it has a very rich set of built in operators including arithmetic, relational, logical, and bitwise operators.
Assignment Operator
int x ; x = 20 ;
Some common notation :- lvalue -- left hand side of an assignment operation rvalue -- right hand side of an assignment operation
Type Conversions :- the value of the right hand side of an assignment is converted to the type of the lvalue. This may sometimes yield compiler warnings if information is lost in the conversion.
For Example :- int x ; char ch ; float f ;
ch = x ; /* ch is assigned lower 8 bits of x, the remaining bits are discarded so we have a possible information loss / x = f ; / x is assigned non fractional part of f only within int range, information loss possible / f = x ; / value of x is converted to floating point */
Multiple assignments are possible to any degree in C, the assignment operator has right to left associativity which means that the rightmost expression is evaluated first.
For Example :- x = y = z = 100 ;
In this case the expression z = 100 is carried out first. This causes the value 100 to be placed in z with the value of the whole expression being 100 also. This expression value is then taken and assigned by the next assignment operator on the left i.e. x = y = ( z = 100 ) ;
Arithmetic Operators
For Example :- int a = 5, b = 2, x ; float c = 5.0, d = 2.0, f ;
x = a / b ; // integer division, x = 2. f = c / d ; // floating point division, f = 2.5. x = 5 % 2 ; // remainder operator, x = 1.
x = 7 + 3 * 6 / 2 - 1 ;// x=15,* and / evaluated ahead of
Note that parentheses may be used to clarify or modify the evaluation of expressions of any type in C in the same way as in normal arithmetic.
x = 7 + ( 3 * 6 / 2 ) - 1 ; // clarifies order of evaluation without penalty x = ( 7 + 3 ) * 6 / ( 2 - 1 ) ; // changes order of evaluation, x = 60 now.
Increment and Decrement Operators
There are two special unary operators in C, Increment ++, and Decrement -- , which cause the variable they act on to be incremented or decremented by 1 respectively.
For Example :- x++ ; /* equivalent to x = x + 1 ; */
++ and -- can be used in prefix or postfix notation. In prefix notation the value of the variable is either incremented or decremented and is then read while in postfix notation the value of the variable is read first and is then incremented or decremented.
For Example :- int i, j = 2 ;
i = ++ j ; /* prefix :- i has value 3, j has value 3 / i = j++ ; / postfix :- i has value 3, j has value 4 */
Special Assignment Operators
Many C operators can be combined with the assignment operator as shorthand notation
For Example :- x = x + 10 ; can be replaced by x += 10 ;
Similarly for -=, *=, /=, %=, etc.
this will give no compilation error to warn us but will compile and assign a value 10 to x when the condition is tested. As this value is non-zero the if condition is deemed true no matter what value x had originally. Obviously this is possibly a serious logical flaw in a program.
Bitwise Operators
These are special operators that act on char or int arguments only. They allow the programmer to get closer to the machine level by operating at bit-level in their arguments.
& Bitwise AND | Bitwise OR ^ Bitwise XOR ~ Ones Complement
Shift Right << Shift left
Recall that type char is one byte in size. This means it is made up of 8 distinct bits or binary digits normally designated as illustrated below with Bit 0 being the Least Significant Bit (LSB) and Bit 7 being the Most Significant Bit (MSB). The value represented below is 13 in decimal.
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 0 0 0 0 1 1 0 1
An integer on a 16 bit OS is two bytes in size and so Bit 15 will be the MSB while on a 32 bit system the integer is four bytes in size with Bit 31 as the MSB.
Bitwise AND, &
RULE : If any two bits in the same bit position are set then the resultant bit in that position is set otherwise it is zero.
For Example :-
Bitwise OR, |
RULE : If either bit in corresponding positions are set the resultant bit in that position is set.
For Example :-
Bitwise XOR, ^
RULE : If the bits in corresponding positions are different then the resultant bit is set.
For Example :-
Shift Operators, << and >>
RULE : These move all bits in the operand left or right by a specified number of places.
Syntax : variable << number of places variable >> number of places
For Example :- 2 << 2 = 8 i.e.
NB : shift left by one place multiplies by 2 shift right by one place divides by 2
Ones Complement
RULE : Reverses the state of each bit.
For Example :-
NB : With all of the above bitwise operators we must work with decimal, octal, or hexadecimal values as binary is not supported directly in C.
The bitwise operators are most commonly used in system level programming where individual bits of an integer will represent certain real life entities which are either on or off, one or zero. The programmer will need to be able to manipulate individual bits directly in these situations. A mask variable which allows us to ignore certain bit positions and concentrate the operation only on those of specific interest to us is almost always used in these situations. The value given to the mask variable depends on the operator being used and the result required.
For Example :- To clear bit 7 of a char variable.
char ch = 89 ; // any value
char mask = 127 ; // 0111 1111
ch = ch & mask ; // or ch &= mask ;
For Example :- To set bit 1 of an integer variable.
int i = 234 ; // any value
int mask = 2 ; // a 1 in bit position 2
i |= mask ;
Implicit & Explicit Type Conversions
Normally in mixed type expressions all operands are converted temporarily up to the type of the largest operand in the expression.