Principles of C and Memory Management

Similar documents
Eastern Mediterranean University School of Computing and Technology Information Technology Lecture7 Strings and Characters

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture5 C Characters and Strings

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Pointers, Arrays, and Strings. CS449 Spring 2016

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

Procedural Programming & Fundamentals of Programming

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Computer Programming: Skills & Concepts (CP) Strings

Write a C program using arrays and structure

C Strings. Abdelghani Bellaachia, CSCI 1121 Page: 1

Procedural Programming

Create a Program in C (Last Class)

Fundamentals of Programming

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

C Programming Language Review and Dissection III

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

struct structure_name { //Statements };

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

int Return the number of characters in string s.

SYSTEM AND LIBRARY CALLS. UNIX Programming 2015 Fall by Euiseong Seo

Chapter 8: Character & String. In this chapter, you ll learn about;

Fundamental of Programming (C)

Pointers, Dynamic Data, and Reference Types

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

COMP 2355 Introduction to Systems Programming

CS 61c: Great Ideas in Computer Architecture

Array Initialization

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

Memory, Arrays & Pointers

ARRAYS(II Unit Part II)

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Characters, Character Strings, and string-manipulation functions in C

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

8. Characters, Strings and Files

Introduction to string

Characters and Strings

Arrays and Strings. CS449 Fall 2017

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Principles of C and Memory Management

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Overview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings

Lectures 5-6: Introduction to C

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Programming. Structures, enums and unions

Computer Programming Unit 3

Programming Language B

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

CS 33. Introduction to C. Part 5. CS33 Intro to Computer Systems V 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Scheme of valuations-test 3 PART 1

CS 222: Pointers and Manual Memory Management

Compiling and Running a C Program in Unix

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Lecture 05 Pointers ctd..

Programming Fundamentals (CS-302 )

Week 8 Lecture 3. Finishing up C

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Computers Programming Course 12. Iulian Năstac

University of Northumbria - School of CEIS A quick guide to C MJB September 2016

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Department of Computer Science and Engineering. Programming for Problem Solving. I Year B.Tech. (I - Sem) Assistant Professor (M.

Arrays, Strings, and Pointers

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

ONE DIMENSIONAL ARRAYS

Chapter 8 Character Arrays and Strings

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Q 1. Attempt any TEN of the following:

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Structure, Union. Ashishprajapati29.wordpress.com. 1 What is structure? How to declare a Structure? Explain with Example

Fundamentals of Programming & Procedural Programming

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CS 11 C track: lecture 6

Computers Programming Course 10. Iulian Năstac


Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

Fundamental of Programming (C)

Object Oriented Pragramming (22316)

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

BSM540 Basics of C Language

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

High Performance Programming Programming in C part 1

2. Blowing your mind with a simple truth

PROGRAMMAZIONE I A.A. 2017/2018

Transcription:

COMP281 Lecture 9 Principles of C and Memory Management Dr Lei Shi

Last Lecture Today Pointer to Array Pointer Arithmetic Pointer with Functions struct Storage classes typedef union String

struct

struct is a user-defined datatype. It combines data of different types. struct It constructs a complex data type which is more meaningful (vs Array). It is a way to package primitive data objects into an aggregate data object

Defining a struct Syntax struct [struct_tag] { /* member variable 1 */ /* member variable 2 */ /* member variable 3 */... [struct_variables]; Variables It s optional to provide the struct a name, but it s better to provide a name. of different datatypes like int, float, char, array etc It s optional to specify one or more struct variables.

Defining a struct Syntax struct [struct_tag] { /* member variable 1 */ /* member variable 2 */ /* member variable 3 */... [struct_variables]; Variables It s optional to provide the struct a name, but it s better to provide a name. of different datatypes like int, float, char, array etc It s optional to specify one or more struct variables. There must be a semicolon(;)!

Defining a struct An example struct Employee { char name[50]; int age; char gender; float salary; struct Employee { char name[50]; int age; char gender; float salary; employee1, employee2;

Accessing struct members struct members have no meaning individually without the struct. To assign a value to a struct member, the member name must be linked with the struct variable using a dot (.) operator. Example 1 #include <stdio.h> #include <string.h> struct Lecturer { char name[50]; char gender; int age; ; int main() { struct Lecturer lec; strcpy(lec.name, "Lei Shi"); lec.gender = 'M'; printf("name: %s\n", lec.name); printf("gender: %c\n", lec.gender); return 0;

Accessing struct members struct members have no meaning individually without the structure. To assign a value to a struct member, the member name must be linked with the struct variable using a dot (.) operator. Example 1 #include <stdio.h> #include <string.h> struct Lecturer { char name[50]; char gender; int age; ; int main() { struct Lecturer lec; strcpy(lec.name, "Lei Shi"); lec.gender = 'M'; printf("name: %s\n", lec.name); printf("gender: %c\n", lec.gender); return 0; Output Name: Lei Shi Gender: M

Initialising struct struct House { int id; float area; ; struct House h1 = {110, 89.6; or struct House h1; h1.id = 110; h1.area = 89.6;

Array of struct int main() { Example 2 for(int i = 0; i < 2; i++) { printf("\nenter record of student %d:\n", i+1); printf("enter name:\t"); #include <stdio.h> scanf("%s", stu[i].name); #include <string.h> printf("enter grade:\t"); struct Student { scanf("%d", &stu[i].grade); char name[10]; printf("\n==========================\n"); int grade; printf("displaying record:\n"); ; printf("==========================\n"); for(int i = 0; i < 2; i++) { struct Student stu[2]; printf("student %d", i+1); printf("\nname is %s", stu[i].name); printf("\ngrade is %d\n",stu[i].grade); printf("------------------\n"); return 0;

Array of struct int main() { Output Example 2 for(int i = 0; i < 2; i++) { Enter record of student 1: printf("\nenter record of student %d:\n", i+1); Enter name: Alan printf("enter name:\t"); #include <stdio.h> Enter grade: 1 scanf("%s", stu[i].name); #include <string.h> printf("enter grade:\t"); Enter record of student 2: struct Student { scanf("%d", &stu[i].grade); Enter name: Blair char name[10]; Enter grade: 2 printf("\n==========================\n"); int grade; printf("displaying record:\n"); ========================== ; printf("==========================\n"); Displaying record: for(int i = 0; i < 2; i++) ========================== { struct Student stu[2]; printf("student %d", Student i+1); 1 printf("\nname is %s", Name stu[i].name); is Alan printf("\ngrade is %d\n",stu[i].grade); Grade is 1 printf("------------------\n"); ------------------ Student 2 return 0; Name is Blair Grade is 2

Nested struct struct Student { char[30] name; int age; /* here Address is a structure */ struct Address { char[50] locality; char[50] city; int pincode; addr; ;

struct as function arguments Passing a struct as a function argument Just like passing any other variable or an array as a function argument Example 3 #include <stdio.h> struct Student { char name[10]; int grade; ; void print(struct Student st) { printf("\nname: %s\n",st.name); printf("\ngrade %d\n",st.grade); int main() { struct Student stu; printf("enter Student record:\n"); printf("enter Name:\t"); scanf("%s", stu.name); printf("enter Grade:\t"); scanf("%d", &stu.grade); print(stu); return 0;

struct as function arguments Passing a struct as a function argument Just like passing any other variable or an array as a function argument Example 3 #include <stdio.h> struct Student { char name[10]; int grade; ; void print(struct Student st) { printf("\nname: %s\n",st.name); printf("\ngrade %d\n",st.grade); int main() { struct Student stu; Output printf("enter Student record:\n"); printf("enter Name:\t"); Enter Student record: scanf("%s", stu.name); printf("enter Enter Grade:\t"); Name: Frans scanf("%d", Enter &stu.grade); Grade: 1 print(stu); return Name: 0; Frans Grade 1

Pointers to struct Example 4 #include <stdio.h> struct point { int x; int y; double dist; ; void init_point(struct point *p) { (*p).x = (*p).y = 0; (*p).dist = 0.0; /* syntactic sugar: */ p->x = p->x = 0; p->dist = 0.0; int main() { struct point p; struct point *pt = &p; init_point(pt); printf("x=%d\n", (*pt).x); return 0;

Pointers to struct Example 4 #include <stdio.h> struct point { int x; int y; double dist; ; void init_point(struct point *p) { (*p).x = (*p).y = 0; (*p).dist = 0.0; /* syntactic sugar: */ p->x = p->x = 0; p->dist = 0.0; int main() { struct point p; struct point *pt = &p; init_point(pt); printf("x=%d\n", (*pt).x); return 0; Output X=0

typedef

Typing struct X all the time is tedious typedef is to assign alternative names typedef to existing datatypes (type alias). It is mostly used with user defined datatypes, when names become complicated to use.

Defining a typedef Syntax typedef <existing_name> <alias_name> For example typedef unsigned long ulong; - Define a term ulong for an unsigned long datatype. - Now this ulong identifier can be used to define unsigned long type variables typedef struct point Point;

Defining a typedef Type component of typedef can also be a struct typedef struct { /* no name for the struct */ int x; int y; double dist; Point p1, p2; /* no "struct" */ Note, this is an anonymous struct

typedef and Pointers typedef can also be used to give an alias name to pointers. /* declaring two pointers? */ int* x, y; /* declare any number of pointers in a single statement */ typedef int* IntPtr; IntPtr x, y, z;

union

union is as special datatype allowing to store different datatypes in the same memory location. union A union can have many members, but only one member can contain a value at any given time. union provides an efficient way of using the same memory location.

Defining a union Syntax union [union_tag] { /* member variable 1 */ /* member variable 2 */ /* member variable 3 */... [union_variables]; Variables It s optional to provide the union a name, but it s better to provide a name. of different types like int, float, char, array etc It s optional to specify one or more union variables.

union vs struct The syntax to declare/define a union is similar to that of a struct union Example struct Example { { int i; int i; float f; float f; char str[20]; char str[20]; e; e;

union vs struct But their usages of memory are different Example 5 #include <stdio.h> #include <string.h> union Data1 { char c;/* 1 bytes */ int i; /* 4 bytes */ double d;/* 8 bytes */ ; struct Data2 { char c;/* 1 bytes */ int i; /* 4 bytes */ double d;/* 8 bytes */ ; int main( ) { union Data1 data1; struct Data2 data2; printf( "Memory size occupied by data1 : %lu\n", sizeof(data1)); printf( "Memory size occupied by data2 : %lu\n", sizeof(data2)); return 0;

union vs struct But their usages of memory are different Example 5 #include <stdio.h> #include <string.h> union Data1 { char c;/* 1 bytes */ int i; /* 4 bytes */ double d;/* 8 bytes */ ; struct Data2 { char c;/* 1 bytes */ int i; /* 4 bytes */ double d;/* 8 bytes */ ; int main( ) { union Data1 data1; struct Data2 data2; printf( "Memory size occupied by data1 : %lu\n", sizeof(data1)); printf( "Memory size occupied by data2 : %lu\n", sizeof(data2)); return 0; Output Memory size occupied by data1 : 8 Memory size occupied by data2 : 16

Accessing union members Similar to struct. To assign a value to a union member, the member name must be linked with the union variable using a dot (.) operator. Example 6.1 #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; ; int main( ) { union Data data; data.i = 66; data.f = 99.9; strcpy( data.str, "comp281"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str); return 0;

Accessing union members Similar to struct. To assign a value to a union member, the member name must be linked with the union variable using a dot (.) operator. Example 6.1 #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; ; int main( ) { union Data data; data.i = 66; data.f = 99.9; strcpy( data.str, "comp281"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); Output printf( "data.str : %s\n", data.str); return 0; data.i : 1886220131 data.f : 293930422431671236884166606848.000000 data.str : comp281

Accessing union members Similar to struct. To assign a value to a union member, the member name must be linked with the union variable using a dot (.) operator. Example 6.1 #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; ; 66 99.9 comp281 Output data.i : 1886220131 data.f : 293930422431671236884166606848.000000 data.str : comp281

Accessing union members The values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory 66 99.9 the value of str comp281 member is location and this is the reason that getting printed as well.

Accessing union members Example 6.2 #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; ; int main( ) { union Data data; data.i = 66; printf( "data.i : %d\n", data.i); data.f = 99.9; printf("data.f : %f\n", data.f); strcpy(data.str, "comp281"); printf("data.str : %s\n", data.str); return 0;

Accessing union members Example 6.2 int main( ) { union Data data; #include <stdio.h> data.i = 66; #include <string.h> printf( "data.i : %d\n", data.i); union Data { int i; data.f = 99.9; float f; printf("data.f : %f\n", data.f); char str[20]; ; strcpy(data.str, "comp281"); printf("data.str : %s\n", data.str); Output data.i : 66 return 0; data.f : 99.900002 data.str : comp281

string

String is a sequence of chars that is treated as a single data item and String terminated by null char '\0'. C does not support string as a datatype A string is actually an array of chars.

Declaring and initialising string variables Example 6.7 #include <stdio.h> #include <string.h> int main () { char msg1[] = {'H','e','l','l','o',',' ',','w','o','r','l','d','!','\0'; char msg2[] = "Hello, world!"; printf("message 1: %s\n", msg1); printf("message 2: %s\n", msg2); printf("length of Message 1 is %lu.\n", sizeof(msg1) / sizeof(msg1[0])); printf("length of Message 2 is %lu.\n", sizeof(msg2) / sizeof(msg2[0])); return 0;

Declaring and initialising string variables Example 6.7 #include <stdio.h> #include <string.h> int main () { char msg1[] = {'H','e','l','l','o',',' ',','w','o','r','l','d','!','\0'; char msg2[] = "Hello, world!"; printf("message 1: %s\n", msg1); printf("message 2: %s\n", msg2); printf("length of Message 1 is %lu.\n", sizeof(msg1) / sizeof(msg1[0])); Output printf("length of Message 2 is %lu.\n", sizeof(msg2) Message 1: / Hello, sizeof(msg2[0])); world! Message 2: Hello, world! return 0; Length of Message 1 is 14. Length of Message 2 is 14.

The string Hello, world! contains 14 chars including '\0' char which is automatically added by the compiler at the end of the string. When initialising a char array by listing all of its characters separately, '\0' char must be provided explicitly.

String functions Method strcat() strcpy() strlen() strcmp() strchr() Description To concatenate(combine) two strings To copy one string into another To show length of a string To compare two strings To search for the first occurrence of the character

String functions strcat() To concatenate(combine) two strings Syntax char *strcat(char *s1, const char *s2); Parameters or Arguments s1: A pointer to a string that will be modified. s2 will be copied to the end of s1. s2: A pointer to a string that will be appended to the end of s1. Returns A pointer to s1 (where the resulting concatenated string resides).

Example 8 #include <stdio.h> #include <string.h> int main() { /* Define a temporary variable */ char str[100]; /* Copy the first string into the variable */ strcpy(str, "The University "); /* Concatenate the following two strings to the end of the first one */ strcat(str, "of Liverpool "); strcat(str, "is established in 1882."); /* Display the concatenated strings */ printf("%s\n", str); return 0;

Example 8 #include <stdio.h> #include <string.h> int main() { /* Define a temporary variable */ char str[100]; /* Copy the first string into the variable */ strcpy(str, "The University "); /* Concatenate the following two strings to the end of the first one */ strcat(str, "of Liverpool "); strcat(str, "is established in 1882."); /* Display the concatenated strings */ printf("%s\n", str); Output return 0; University of Liverpool is established in 1882.

String functions strcpy() To copy one string into another Syntax char *strcpy(char *dest, const char *src) Parameters or Arguments dest: the pointer to the destination array where the content is to be copied. src: the string to be copied. Returns A pointer to the destination string dest.

Example 9 #include <stdio.h> #include <string.h> int main() { char src[40]; char dest[100]; strcpy(src, "This is COMP281."); strcpy(dest, src); printf("final copied string : %s.\n", dest); return 0;

Example 9 #include <stdio.h> #include <string.h> int main() { char src[40]; char dest[100]; strcpy(src, "This is COMP281."); strcpy(dest, src); printf("final copied string : %s.\n", dest); return 0; Output Final copied string : This is COMP281

String functions strlen() To show length of a string Syntax size_t strlen(const char *s); Parameters or Arguments s: the string whose length is to be found. Returns The length of the string pointed to by s. It does NOT include the null character in the length calculation. '\0'

Example 10 #include <stdio.h> #include <string.h> int main() { char str[50]; int len; strcpy(str, "Hello, world!"); len = strlen(str); printf("length of %s is %d \n", str, len); return 0;

Example 10 #include <stdio.h> #include <string.h> int main() { char str[50]; int len; strcpy(str, "Hello, world!"); len = strlen(str); printf("length of %s is %d \n", str, len); return 0; Output Length of Hello, world! is 13

String functions strcmp() To compare two strings Syntax int strcmp(const char *str1, const char *str2) Parameters or Arguments str1: the first string to be compared str2: the second string to be compared Returns 0 if s1 and s2 are the same; Less than 0 if s1<s2; Greater than 0 if s1>s2.

Example 11 #include <stdio.h> #include <string.h> int main() { char str1[50]; char str2[50]; int ret; strcpy(str1, "012345"); strcpy(str2, "O12345"); ret = strcmp(str1, str2); if(ret < 0) { printf("str1 is less than str2.\n"); else if(ret > 0) { printf("str2 is less than str1.\n "); else { printf("str1 is equal to str2.\n "); return 0;

Example 11 #include <stdio.h> #include <string.h> int main() { char str1[50]; char str2[50]; int ret; strcpy(str1, "012345"); strcpy(str2, "O12345"); ret = strcmp(str1, str2); if(ret < 0) { printf("str1 is less than str2.\n"); else if(ret > 0) { printf("str2 is less than str1.\n "); else { printf("str1 is equal to str2.\n "); Output return 0; str1 is less than str2.

String functions strchr() To search for the first occurrence of the character Syntax char *strchr(const char *str, int c) Parameters or Arguments str: the string to be searched in c: the character to be searched for Returns A pointer to the first occurrence of the character c in the string str, or NULL if the character is not found.

Example 12 #include <stdio.h> #include <string.h> int main() { const char str[] = "https://www.liverpool.ac.uk"; const char ch = '.'; char *ret; ret = strchr(str, ch); printf("string after %c is - %s \n", ch, ret); return 0; Output String after. is -.liverpool.ac.uk

String functions char *strncat(char *dest, const char *src, size_t n) int strcoll(const char *str1, const char *str2) char *strncpy(char *dest, const char *src, size_t n) char *strerror(int errnum) char *strpbrk(const char *str1, const char *str2) char *strrchr(const char *str, int c) size_t strspn(const char *str1, const char *str2) char *strtok(char *str, const char *delim) size_t strxfrm(char *dest, const char *src, size_t n)

Don t forget #include <string.h>

Storage classes

Storage classes Each variable has a storage class which decides the following things: Scope: where the value of the variable would be available inside a program. Default initial value: default initial value if NOT explicitly initialised. Life time: for how long will that variable exist. The following storage classes are mostly used: Automatic variables External variables Static variables Register variables

Automatic variables Each variable has a storage class which decides the following things: Scope: local to the function block inside which they are defined. Default initial value: any random value i.e. garbage value. Life time: till the end of the function/method block where the variable is defined. { int detail; /* by default it s an 'auto' */ /* or */ auto int details;/* Both are same */ return 0;

External or Global variable Each variable has a storage class which decides the following things: Scope: not bound by any function; available everywhere. Default initial value: 0(zero). Life time: Till the program doesn't finish its execution.

Global values can be changed by any function in the program!

Example 13 #include <stdio.h> int number; /* global variable */ void fun1() { number = 20; printf("i am in function fun1. My value is %d.\n", number); void fun2() { printf("i am in function fun2. My value is %d.\n", number); int main() { number = 10; printf("i am in main function. My value is %d\n", number); fun1(); /* function calling, discussed in next topic */ fun2(); /* function calling, discussed in next topic */ return 0;

Example 13 #include <stdio.h> int number; /* global variable */ void fun1() { number = 20; printf("i am in function fun1. My value is %d.\n", number); void fun2() { printf("i am in function fun2. My value is %d.\n", number); int main() { number = 10; printf("i am in main function. My value is %d\n", number); fun1(); /* function calling, discussed in next topic */ I am in main function. My value is 10 I am in function fun1. My value is 20. I am in function fun2. My value is 20. fun2(); /* function calling, discussed in next topic */ return 0; Output

Keyword extern The extern keyword is used with a variable to inform the compiler that this variable is declared somewhere else. The extern declaration does not allocate storage for variables. file1.c #include <stdio.h> /* global variable */ int a = 7; void func() { a++; printf("%d", a); file2.c #include "file.c"; int main() { extern int a; func(); return 0;

Problem when extern is not used int main() { a = 10; /* Error: cannot find definition of variable 'a' */ printf("%d", a); return 0; Example using extern in same file int main() { extern int x; /* informs the compiler that it is defined somewhere else */ x = 10; printf("%d", x); int x; //Global variable x

Static variables Tells the compiler to persist/save the variable until the end of program Scope: local to the block in which the variable is defined. Default initial value: 0(zero). Life time: Till the whole program doesn't finish its execution. Instead of creating and destroying a variable every time when it comes into and goes out of scope, static variable is initialised only once and remains into existence till the end of the program.

Example 14 #include <stdio.h> void test(); int main() { test(); test(); test(); return 0; void test() { static int a = 0; /* a static variable */ a = a + 1; printf("%d\t",a); Output 1 2 3

Register variables Tells the compiler to persist/save the variable until the end of program Scope: local to the function in which it is declared. Default initial value: Any random value i.e garbage value. Life time: Till the end of function/method block, in which the variable is defined. Syntax register int number;

Register variables inform the compiler to store the variable in CPU register instead of memory. Register variables have faster accessibility than a normal variable. Generally, the frequently used variables are kept in registers. But only a few variables can be placed inside registers. We can never get the address of such variables.

Which storage class should be used and when?

To improve the speed of execution of the program and to carefully use the memory space occupied by the variables: Use static storage class only when we want the value of the variable to remain same every time we call it using different function calls. Use register storage class only for those variables that are used in our program very often. CPU registers are limited and thus should be used carefully. Use external or global storage class only for those variables that are being used by almost all the functions in the program. If we do not have the purpose of any of the above mentioned storage classes, then we should use the automatic storage class.

Summary

Today struct Storage classes Next typedef union String Dynamic Memory Allocation Stack and Heap