C Programming "°º - Calypso - º°"
C Programming "°º - Calypso - º°"
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 1
C History
• C is a programming language. The C language
was first developed in 1972 by Dennis Ritchie
at AT&T Bell Labs.
• Many ideas came from type less languages BCPL
and B
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 2
Introduction To C
• C is a high-level programming language.
– In the computer world, the further a programming language is from the
computer architecture, the higher the language's level. The high-level
programming languages, on the other hand, are closer to our human
languages.
• High-level programming languages, including C, have the following
advantages:
– Readability: Programs are easy to read.
– Maintainability: Programs are easy to maintain.
– Portability: Programs are easy to port across different computer platforms.
• C allows you to get control of computer hardware and peripherals.
That's why the C language is sometimes called the lowest high-level
programming language.
• Case – sensitive.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 3
Introduction To C cont…
• C's syntax is terse and the language does not restrict what
is "allowed" -- the programmer can pretty much do
whatever they want.
• C's type system and error checks exist only at compile-
time. The compiled code runs in a stripped down run-time
model with no safety checks for bad type casts, bad array
indices, or bad pointers. There is no garbage collector to
manage memory. Instead the programmer manages heap
memory manually. All this makes C fast but fragile.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 4
Why ‘C’ Language is required?
• Of higher level languages, C is the closest
to assembly languages
– bit manipulation instructions
– pointers (indirect addressing)
• Most microcontrollers have available C
compilers
• Writing in C simplifies code development
for large projects
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 5
C is a powerful and flexible language
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 6
Tools Availability
• A wide variety of C compilers and helpful
accessories are available for wide range of
machines and platforms
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 7
C is a portable language
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 9
Compilation Process
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 10
Step 1
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 11
Step 2
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 13
Step 4
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 14
Compiling and Linking
• Compiler – translates .c file to machine
Source Code = .c
understandable language.
• Linker - to link together the object file,
Compiler the ANSI standard C library, and other
user-generated libraries to produce an
executable file—the binary code.
Object file = .o/.obj • The .obj and .exe files are both machine-
dependent.
Linker • All errors found by the compiler and
linker must be fixed before an .exe file
can be made.
Executable File = .exe
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 15
Writing Your First C Program…
• File name
• Comments - /* */, //, nested?
• #include
• main()
• printf(), “\n”
• return()
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 16
First C Program
1: #include <stdio.h>
2: main()
3: {
4: printf("Hello, World!\n");
5: return 0;
6: }
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 17
On TurboC IDE
• Press Alt+F9 to Preprocess, Compile and
Assemble
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 18
C Data Types
Data types
All C variables are defined with a specific type. C has the
following built-in types.
char - characters
int - integers (whole numbers)
float -real numbers
void - valueless
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 20
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 21
C Data Types (contd.)
1. char :
a) Occupy 1 byte
b) Much be enclosed with in single
quotes(‘’)
c) Format specifier is %c
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 22
C Data Types (contd.)
2. int :
a) Depending on the operating system and the C
compiler you're using, the length of an integer varies
b) Format Specifier is %d
c)No special char with in the integer constant
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 23
C Data Types (contd.)
3. float :
a) Occupies 4 bytes
b) Format specifier is %f
c) No special character
within the float constant
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 24
Expressions
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 25
Definition
• In C, an expression is anything that
evaluates to a numeric value. C expressions
come in all levels of complexity
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 26
Simple Expressions
• The simplest C expression consists of a single
item: a simple variable, literal constant, or
symbolic constant. Here are four expressions
Expression Description
PI A symbolic constant
(defined in the program)
20 A literal constant
rate A variable
-1.25 Another literal
07/12/21 constant
¨˜”°º•Calypso•º°”˜¨ 27
Evaluation of expressions
• A literal constant evaluates to its own
value. A symbolic constant evaluates to the
value it was given when you created it
using the #define directive. A variable
evaluates to the current value assigned to it
by the program.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 28
Complex Expressions
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 29
Complex expressions
• Example:
1.25 / 8 + 5 * rate + rate * rate / cost
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 30
Interesting
• C expressions get even more interesting
Example:
i) x = a + 10;
ii) y = x = a + 10;
iii) x = 6 + (y = 4 + 5);
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 31
Operators
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 32
Data Manipulation with Operators
(contd.)
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 34
More Operators
• Measuring Data Sizes
– sizeof (expression)
• Logical Operators:
• && : Logical AND
• || : Logical OR
• ! : Logical negation operator
• Bit-Manipulation Operators:
• & : Bitwise AND operator
• | : Bitwise OR operator
• ^ : Bitwise exclusive OR (XOR) operator
• ~ : Bitwise complement operator
• >> : Right-shift operator
07/12/21 • << : Left-shift operator
¨˜”°º•Calypso•º°”˜¨ 35
More Operators (contd.)
• Conditional Operator:
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 36
Operators Precedence chart
Symbol Meaning
++ -- post increment /
decrement
() function call
[] array element
-> pointer to structure
member
. structure or union
member
++ -- pre increment /
decrement
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 37
!~ logical NOT, bitwise NOT
^ bitwise exclusive OR
| bitwise OR
&& logical AND
|| logical OR
?: conditional
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 39
= += /= %= += -= assignment, compound
<<= >>= &= ^= |= assignment
, comma
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 40
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 41
Anatomy of a C Function
• Function type:
– type of value a function is going to return after its execution
• Function name:
– Choose a name that reflects what the function can do.
• Arguments to the function:
– information passed to functions are known as arguments.
– An argument list contains two or more arguments that are
separated by commas.
• Opening & closing brace:
– braces are used to mark the beginning and end of a function /
statement block.
• Function body:
– contains variable declarations and C statements
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 42
C Keywords (ANSI’89)*
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 43
Variables
• A variable is a named data storage location in your
computer's memory. By using a variable's name in
your program, you are, in effect, referring to the
data stored there.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 44
Rules To Create Variable Names
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 45
Rules To Create Variable Names
Cont…
• Case matters (that is, upper- and lowercase
letters). Thus, the names count and Count
refer to two different variables
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 46
Constants
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 47
Literal Constants
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 48
Symbolic Constants
• A symbolic constant is a constant that is
represented by a name (symbol) in your
program.
• Like a literal constant, a symbolic constant
can't change
• Whenever you need the constant's value in
your program, you use its name as you would
use a variable name
• The actual value of the symbolic constant
needs to be entered only once, when it is first
defined
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 49
How to Create a Symbolic constant
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 50
Data Modifiers
• Data Modifiers enable you to have greater control
over the data:
1. signed 2. unsigned
3. short 4. long
• The signed Modifier:
• Used to enable the sign bit.
• Used to indicate to the compiler that the int or char
data type uses the sign bit.
• All int variables in C are signed by default.
• The unsigned Modifier:
• used to tell the C compiler that no sign bit is needed in the
specified data type.
• Like the signed modifier, the unsigned modifier is
meaningful only to the int and char data types
07/12/21 ¨˜”°º•Calypso•º°”˜¨
• By default, ‘unsigned’ means ‘unsigned int’. 51
Data Modifiers (contd.)
• The short Modifier:
• A data type can be modified to take less memory by
using the short modifier.
• By default, a short int data type is a signed number.
• %hd, %hi or % hu is to specify that the corresponding
number is a short int or unsigned short int.
• The long modifier:
• It is used to define a data type with increased storage
space.
• The ANSI standard allows you to indicate that a
constant has type long by suffixing l or L to the
constant.
• %ld or %Ld specifies that the corresponding datum is
long int. %lu or %Lu is then used for the long unsigned
int data.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 52
Memory map of a C program
Stack
Heap
Global variables
Program code
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 53
Variables
A variable is a named location in memory that is used to
hold a value that can be modified by the program.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 54
The 4 C scopes:
file scope: Starts at the beginning of the file and ends with
the end of the file. It refers only to those identifiers that
are declared outside of all functions. Variables that have
file scope are global.
block scope: Begins with the opening { of a block & ends
with its associated closing }. However, block scope also
extends to function parameters in a function definition.
Variables with block scope are local to their block.
function prototype scope: Identifiers declared in a function
prototype; visible within the prototype.
function scope: Begins with the opening { of a function &
ends with its closing }. Functions scope applies only to
labels. A label is used as the target of goto statement, and
that label must be within
07/12/21
the same function as the goto.
¨˜”°º•Calypso•º°”˜¨ 55
%c character format specifier.
%d Integer format specifier.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 58
Control Flow statements
• The if statement
• The if-else statement
• The switch statement
• The break statement
• The continue statement
• The goto statement
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 59
The if statement
• Used to evaluate the conditions as well as to make the
decision whether the block of code controlled by the
statement is going to be executed.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 60
The if-else Statement
• If you want the computer to execute some other
specified statements when the conditional
expression of the if statement is logical FALSE
• if (expression)
{
statement1;
...
}
else
{
statement_A;
…
}
07/12/21 • Nested if statements.
¨˜”°º•Calypso•º°”˜¨ 61
The switch Statement
• Used to make (almost) unlimited decisions or choices
based on the value of a conditional expression and
specified cases.
switch (expression)
{
case expression1:
statement1;
case expression2:
statement2;
...
default:
statement-default;
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 62
break & continue
break;
• Break an infinite loop.
• to exit the switch construct after the statements within a
selected case are executed.
continue;
• Instead of breaking a loop, there are times when you
want to stay in a loop but skip over some statements
within the loop. To do this, you can use the continue
statement provided by C. The continue statement
causes execution to jump to the top of the loop
immediately.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 63
goto
• The general form is:
statement1;
label: statement2;
...
goto label;
• label is a label name that tells the goto statement where to
jump. You have to place label in 2 places:
– One is at the place where the goto statement is going to jump (note
that a colon must follow the label name),
– and the other is the place following the goto keyword.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 65
Looping Under the for statement
for (expression1; expression2; expression3)
{
statement1;
statement2;
...
}
• expression1: initializes one or more variables. Exp1 is only evaluated
once when the for statement is first encountered.
• expression2: is the conditional part. Evaluated right after the
evaluation of exp1 and then is evaluated after each successful looping
by the for statement.
• Expression3: not evaluated when the for statement is first encountered.
Exp3 is evaluated after each looping and before the statement goes
back to test expression2 again.
while (expression)
{
statement1;
...
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 68
Functions in C
• A function definition is always given first, before the function
is called from a main() function.
Declaration vs Definition:
• The declaration of a variable or function specifies the
interpretation and attributes of a set of identifiers.
• The definition requires the C compiler to reserve storage
for a variable or function named by an identifier.
• A variable declaration is a definition, but a function
declaration is not.
Specifying Return Types:
• A function can be declared to return any data type, except
an array or function. The return statement used in a
function definition returns a single value whose type
should match the one declared in the function declaration.
• By default, the return type of a function is int.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 69
Functions in C(contd.)
• Using Prototypes:
data_type_specifier function_name
(
data_type_specifier argument_name1,
data_type_specifier argument_name2,
. . .
data_type_specifier argument_nameN
);
eg.: int i;
i = rand();
or
int getchar(void);
int c;
c = getchar();
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 71
Functions in C(contd.)
• Functions with a Fixed Number of Arguments:
int function_1(int x, int y);
• To declare a function with a fixed number of arguments,
you need to specify the data type of each argument.
• It's recommended to indicate the argument names so that
the compiler can have a check to make sure that the
argument types and names declared in a function
declaration match the implementation in the function
definition.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 72
Functions in C(contd.)
• Prototyping a Variable Number of Arguments:
• The ellipsis token ... (i.e., three dots) represents a variable
number of arguments
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 78
Strings
• What Is a String? string is a character array terminated
by a null character (\0)
char array_ch[4] = {`H', `i‘, `!',‘\0'};
• Initializing Strings:
char arr_str[7] = {`H', `e', `l', `l',
`o', `!', '\0'};
• char str[7] = "Hello!";
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 79
• char str[] = "Hello!";
Manipulating Strings(contd.)
• String Constants Versus Character Constants:
– Differnce between: char ch = `x';
char str[] = "x";
• String as a char pointer:
char *ptr_str;
ptr_str = "A character string.";
• Multidimensional arrays
C supports multidimensional arrays.
type name[size1][size2]…[sizeN]
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 80
Manipulating Strings(contd.)
• String Constants Versus Character Constants:
– Difference between: char ch = `x'; 1B
char str[] = "x";
2B
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 81
An Introduction to
Pointers
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 82
• What Is a Pointer?
A pointer is a variable whose value is used to point to (point
to location of) another variable.
• Address operator ( &) The & is a unary operator that returns
memory address of its operand.
– %p, %u
• Dereference Operator ( * ) this unary operator returns the
value located at the address that follows.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 83
Pointer Arithmetic
The position of a pointer can be changed by adding or subtracting
integers to or from the pointer.
pointer_name + n;
• It indicates to the compiler to move to the memory location that is ‘n’
memory locations away from the current position of pointer_name.
• ‘n’ is an integer whose value can be either positive or negative.
• When the C compiler reads the pointer_name + n expression, it
interprets the expression as
pointer_name + n * sizeof(data_type_specifier)
• Pointer Subtraction
For two pointers of the same type, you can subtract one
pointer value from the other. For instance, given two char
pointer variables, ptr_str1 and ptr_str2, you can calculate the
offset between the two memory locations pointed to by the
two pointers like this:
07/12/21
ptr_str2 - ptr_str1
¨˜”°º•Calypso•º°”˜¨ 84
Arrays and Pointers
• We can make a pointer that refers to the first
element of an array by simply assigning the array
name to the pointer variable.
– A pointer is said to refer to an array when the address of the first
element in the array is assigned to the pointer. The address of the
first element in an array is also called the start address of the array.
– To assign the start address of an array to a pointer, you can either
put the combination of the address-of operator (&) and the first
element name of the array, or simply use the array name, on the
right side of an assignment operator (=).
• Displaying Arrays of Characters
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 85
Arrays and Pointers(contd.)
• The Null Character (\0)
– A character array is considered a character string in C if
the last element in the array contains a null character
(\0).
• Multidimensional Arrays
• Unsized Arrays
– The compiler can automatically calculate the memory
space needed by an unsized array.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 86
Pointers and Arrays
• Accessing Arrays via Pointers:
An array name that is not followed by a subscript is
interpreted as a pointer to the first element of the array.
• You can assign the start address of the array to a pointer of the
same data type; then you can access any element in the array
by adding a proper integer to the pointer. The value of the
integer is the same as the subscript value of the element that
you want to access.
int list[] = {1, 2, 3, 4, 5};
int *ptr_int;
ptr_int = list;
then,
*(ptr_int + 2) = -3; || list[2] = -3;
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 87
Pointers and Functions
• Passing Arrays to Functions:
One way to save the number of arguments passed to a
function is to use arrays. You can put all variables of the
same type into an array, and then pass the array as a single
argument.
void function(int list[]);
void main()
{
int array[] = {1,2,3,4,5};
function(array);
}
void function(int list[])
{
int i;
for(i=0; i<6; i++) printf(“\n\t%d”,list[i]);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 88
Pointers and Functions
• Passing Arrays to Functions:
One way to save the number of arguments passed to a function
is to use arrays. You can put all variables of the same type
into an array, and then pass the array as a single argument.
void function(int list[]);
void main()
{
int array[] = {1,2,3,4,5};
function(array);
}
void function(int list[])
{
int i;
for(i=0; i<6; i++) printf(“\n\t%d”,list[i]);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 89
Pointers and Functions
• Passing Pointers to Functions:
An array name that is not followed by a subscript is interpreted as
a pointer to the first element of the array. The address of the first
element in an array is the start address of the array. Hence, you
can assign the start address of an array to a pointer, and then pass
the pointer name, instead of the unsized array, to a function.
void chprint(char *ptr);
void main()
{
char array[] = {"\nIts time for a break!!!"};
char *ch_ptr;
ch_ptr = array;
chprint(ch_ptr);
}
void chprint(char *ptr)
{
printf("\n%s",ptr);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 90
Pointers and Functions
• Passing Pointers to Functions:
An array name that is not followed by a subscript is interpreted as
a pointer to the first element of the array. The address of the first
element in an array is the start address of the array. Hence, you
can assign the start address of an array to a pointer, and then pass
the pointer name, instead of the unsized array, to a function.
void chprint(char *ptr);
void main() Variable name not
{ necessary, can be
char array[] = {"\nIts time for a break!!!"};
char *ch_ptr;
different.
ch_ptr = array;
chprint(ch_ptr);
}
void chprint(char *ptr)
{
printf("\n%s",ptr);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 91
Pointers and Functions(contd.)
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 92
Pointers and Functions(contd.)
• Arrays of Pointers:
data_type_specifier *pointer_name[size];
eg. int *ptr_int[9];
void strprint(char **str1, int size) ;
main()
{
char *str[3] = {“\nba-ba", “ black", “
sheep”};
int i, size = 3;
strprint (str, size); }
void strprint(char **str1, int size)
{ int i;
for (i=0; i<size; i++) /* Print all
strings in an array of
pointers to trings */
printf("%s", str1[i]);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 93
Pointing to Functions
#include <stdio.h>
int StrPrint(char *str);/*function declaration */
main()
{
char str[24] = "Pointing to a function.";
int (*ptr)(char *str);
ptr = StrPrint;
if (!(*ptr)(str)) printf("Done!\n");
return 0;
}
int StrPrint(char *str) /* function definition */
{
printf("%s\n", str);
return 0;
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 94
C’s Dynamic Allocation Functions
Allocating Memory at Runtime:
When you do not know the exact sizes of arrays used in
your programs, until much later when your programs
are actually being executed.
– malloc() function
– calloc() function
– realloc() function
– free() function
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 95
Allocating Memory(contd.)
• The malloc() Function:
• The malloc() function to allocate a specified size of
memory space.
• The syntax for the malloc() function is
#include <stdlib.h>
void *malloc(size_t size);
Here size indicates the number of bytes of storage to
allocate.
• The malloc() function returns a void pointer.
• If the malloc() function fails to allocate a piece of
memory space, it returns a null pointer.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 96
Allocating Memory(contd.)
• Releasing Allocated Memory with free():
Because memory is a limited resource, you should
allocate an exactly sized piece of memory right
before you need it, and release it as soon as you
don't need it.
ptr_int = malloc(max * sizeof(int));
/* call malloc() */
…
…
free(ptr_int);
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 97
Allocating Memory(contd.)
• The calloc() Function:
– The differences between malloc() and calloc() are
that the latter takes two arguments and that the memory
space allocated by calloc() is always initialized to 0.
There is no such guarantee that the memory space
allocated by malloc() is initialized to 0.
– The syntax for the calloc() function is
#include <stdlib.h>
void *calloc(size_t nitem, size_t size);
– Here nitem is the number of items you want to save in the
allocated memory space. size gives the number of bytes
that each item takes. The calloc() function returns a
void pointer too.
– If the calloc() function fails to allocate a piece of
memory space, it returns a null pointer.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 98
Allocating Memory(contd.)*
• The realloc() Function:
• The realloc() function gives you a means to change the
size of a piece of memory space allocated by the malloc()
function, the calloc() function, or even itself.
• The syntax for the realloc() function is
#include <stdlib.h>
void *realloc(void *block, size_t size);
• Here block is the pointer to the start of a piece of memory
space previously allocated. size specifies the total byte
number you want to change to.
• The realloc() function returns a void pointer.
• The realloc() function returns a null pointer if it fails to
reallocate a piece of memory space.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 99
More Data Types and Functions
• Declaring Unions
union union_tag
{
data_type1 variable1;
data_type2 variable2;
...
} union variable1, …, union variableN;
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 111
Unions(contd.)
• Defining Union Variables:
Union variables can be defined after declaring a union.
union | union uni_name
{ | {
int a; | int a;
char c[10]; | char c[10];
float f; | float f;
}name1, name2; | };
| union uni_name name1,name2;
• Referring a Union with . or ->
The dot operator (.) can be used in referencing union members.
The arrow operator (->)is used to reference the union member
year with the pointer ptr.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 112
Unions(contd.)*
• Initializing a Union:
• The memory location of a union is shared by different
members of the union at different times. The size of a union
is equal to the size of the largest data item in the list of the
union members, which is large enough to hold any members
of the union, one at a time.
• Therefore, it does not make sense to initialize all members of
a union together because the value of the latest initialized
member overwrites the value of the preceding member.
• Initialize a member of a union only when you are ready to
use it. The value contained by a union is the value that is
latest assigned to a member of the union.
main(void)
{
union u val; int x;
x = UnionInitialize(val);
printf("The 2 character constants held by the
union:\n");
printf("%c\n", x & 0x00FF); printf("%c\n", x >> 8);
return 0;
}
int UnionInitialize(union u val)/*function definition*/
{val.ch[0] = `H'; val.ch[1] = `i'; return val.num;}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 114
Unions(contd.)
There are 2 kinds of union applications:
struct tag_name
{
data_type name1: length1;
data_type name2: lenght2;
. . .
data_type nameN: lengthN;
} variable_list;
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 116
Q&A
• Q. What will happen if you initialize all
members of a union together?
• Q. Can you access the same memory
location with different union members?
• What Is a File?
A file represents a concrete device(a disk file, a terminal, a
printer, or a tape drive) with which you want to exchange
information. Before you perform any communication to a file,
you have to open the file. Then you need to close the opened
file after you finish exchanging information with it.
• What Is a Stream?
The data flow you transfer from your program to a file, or
vice versa, is called a stream, which is a series of bytes. To
perform I/O operations, you can read from or write to any
type of files by simply associating a stream to the file.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 119
The Basics of Disk File I/O*
• Pointers of FILE
A pointer of type FILE is called a file pointer, which references
a disk file. A file pointer is used by a stream to conduct the
operation of the I/O functions.
Eg., the following defines a file pointer called fptr:
FILE *fptr;
• Opening a File:
fopen() gives you the ability to open a file and associate a
stream to the opened file. You need to specify the way to open a
file and the filename with the fopen() function. The syntax
for the fopen() function is:
#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 120
• Opening a File(contd.):*
The fopen() function returns a pointer of type FILE. If an
error occurs during the procedure to open a file, the fopen()
function returns a null pointer.
• The following list shows the possible ways to open a file by various strings
of modes:
"r" opens an existing text file for reading.
"w" creates a text file for writing.
"a" opens an existing text file for appending.
"r+" opens an existing text file for reading or writing.
"w+" creates a text file for reading or writing.
"a+" opens or creates a text file for appending.
"rb" an existing binary file for reading.
"wb" creates a binary file for writing.
"ab" opens an existing binary file for appending.
"r+b" opens an existing binary file for reading or writing.
"w+b" creates a binary file for reading or writing.
"a+b"
07/12/21 opens or creates a binary file for appending.
¨˜”°º•Calypso•º°”˜¨ 121
• Closing a File:
After a disk file is read, written, or appended with
some new data, you have to disassociate the file
from a specified stream by calling the fclose()
function.
The syntax for the fclose() function is
#include <stdio.h>
int fclose(FILE *stream);
If fclose() closes a file successfully, it returns
0. Otherwise, the function returns EOF.
#include <stdio.h>
char *fgets(char *s, int n, FILE *stream);
#include <stdio.h>
int fputs(const char *s, FILE *stream);
#include <stdio.h>
long ftell(FILE *stream);
• The general form to use the #ifdef and #endif directives is:
#ifdef macro_name
statement1
Statement
. . .
statementN
#endif