typedef int Array[10]; String name; Array ages;

Similar documents
Fundamental of Programming (C)

Structures and Unions in C. Alan L. Cox

Programming for Engineers Structures, Unions

OBJECT ORIENTED PROGRAMMING USING C++

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

C Structures, Unions, Bit Manipulations, and Enumerations

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Chapter 10 C Structures, Unions, Bit Manipulations

AIMMS Function Reference - Date Time Related Identifiers

Low-Level Programming in C

CS Programming I: Arrays

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -STRUCTURE- SPRING 2015 SEON-JU AHN, CNU EE

Type Definition. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18

by: Lizawati, Norhidayah & Muhammad Noorazlan Shah Computer Engineering, FKEKK, UTeM

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

CS349/SE382 A1 C Programming Tutorial

Example. Section: PS 709 Examples of Calculations of Reduced Hours of Work Last Revised: February 2017 Last Reviewed: February 2017 Next Review:

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Fundamentals of Programming Session 24

ALQUDS University Department of Computer Engineering

Syntax and Variables

Functions and Recursion

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

A class is a user-defined type. It is composed of built-in types, other user-defined types and

High Performance Computing

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$

INFORMATION TECHNOLOGY SPREADSHEETS. Part 1

14. Other Data Types. Compound Data Types: Defined data types (typedef) Unions typedef existing_type new_type_name ;

Data Structures and Algorithms (DSA) Course 4. Iulian Năstac

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays and Pointers (part 2) Be extra careful with pointers!

History. used in early Mac development notable systems in Pascal Skype TeX embedded systems

BLM2031 Structured Programming. Zeyneb KURT

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Conditional Formatting

Operator overloading: extra examples

Structures and Union. Fall Jinkyu Jeong GEBD029: Basis and Practice in Programming Fall 2014 Jinkyu Jeong

Fundamental of Programming (C)

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

EEE145 Computer Programming

Arrays III and Enumerated Types

Structured Data. CIS 15 : Spring 2007

Schedule/BACnet Schedule

C: How to Program. Week /Mar/05

A Fast Review of C Essentials Part I

IV Unit Second Part STRUCTURES

Recursion Enums. Basics of Programming 1. Department of Networked Systems and Services G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A.

Chapter 11: Structured Data

Complex data structures. Cedric Saule

CS 141, Introduction to Computer Science Fall Midterm Exam

Do not turn to the next page until the start of the exam.

Programming Assignment #2

Calendar PPF Production Cycles Non-Production Activities and Events

Helping You C What You Can Do with SAS

Tokens, Expressions and Control Structures

BHARATI VIDYAPEETH`S INSTITUTE OF MANAGEMENT STUDIES AND RESEARCH NAVI MUMBAI ACADEMIC CALENDER JUNE MAY 2017

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

Grade 4 Mathematics Pacing Guide

Structures Unions and Enumerated Datatypes 224

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

CIMA Asia. Interactive Timetable Live Online

CIMA Certificate BA Interactive Timetable

DATE OF BIRTH SORTING (DBSORT)

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

MONITORING REPORT ON THE WEBSITE OF THE STATISTICAL SERVICE OF CYPRUS DECEMBER The report is issued by the.

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

Chapter 11: Structured Data

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

Lecture 3. The syntax for accessing a struct member is

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Arrays. What if you have a 1000 line file? Arrays

Data Types and Variables in C language

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

LECTURE 11 STRUCTURED DATA

Chapter 9 Technicalities: Classes, etc. Walter C. Daugherity Lawrence Pete Petersen Bjarne Stroustrup Fall 2007

Fundamentals of Programming

Chapter 6 Reacting to Player Input

This is part of the book COMPUTER PROGRAMMING THE C LANGUAGE. by Adriana ALBU. Conspress Publisher, Bucureşti, România, 2013 ISBN:

Structures. Today s Goals. Structure Operations. Structure Type Declaration. Struct Instance. typedef. CS246 Lec12. Structures

12 CREATING NEW TYPES

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

13. Data Structures. struct type_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3;..

Lecture 14. Dynamic Memory Allocation

CS3157: Advanced Programming. Announcement

Fundamentals of Programming Session 23

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

Chapter 11: Abstract Data Types. Abstraction and Data Types. Combining Data into Structures 8/23/2014. Abstract Data Types

Chapter 2 - Introduction to C Programming

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

CIMA Asia. Interactive Timetable Live Online

Ch 6-2. File Input / Output

PROGRAMMAZIONE I A.A. 2017/2018

CS201 - Introduction to Programming Glossary By

Fundamentals of Programming Session 25

Scheduling. Scheduling Tasks At Creation Time CHAPTER

Input And Output of C++

Arrays. Arrays (8.1) Arrays. One variable that can store a group of values of the same type. Storing a number of related values.

Transcription:

Morteza Noferesti

The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; Length a, b, len ; Length numbers[10] ; makes the name Length a synonym (or alias) for the data type int. The data type name Length can now be used in declarations in exactly the same way that the data type int can be used: typedef char String[50]; typedef int Array[10]; String name; Array ages; 2

Structures sometimes referred to as aggregates are collections of related variables under one name Structures may contain variables of many different data types in contrast to arrays that contain only elements of the same data type Structures are commonly used to define records Pointers and structures facilitate the formation of more complex data structures such as linked lists, queues, stacks and trees Structures are derived data types they are constructed using objects of other types 3

struct employee }; char firstname[ 20 ]; char lastname[ 20 ]; int age; char gender; double hourlysalary; struct employee char firstname[ 20 ]; char lastname[ 20 ]; int age; char gender; double hourlysalary; } Ali, Sara, empdts[20]; The name "employee" is called a structure tag 4

Members of the same structure type must have unique names, but two different structure types may contain members of the same name without conflict struct employee char Name[ 20 ]; char Name[ 20 ]; // Error!!! int age; char gender; double hourlysalary; } Ali, Sara, empdts[20]; struct employee Reza, *emp; Each structure definition must end with a semicolon 5 struct Student char Name[ 20 ]; // OK int age; char gender; }; struct Student Ce40153[80];

A structure cannot contain an instance of itself For example, a variable of type struct employee cannot be declared in the definition for struct employee A pointer to struct employee, however, may be included struct employee // double hourlysalary; struct employee person; /* ERROR */ struct employee *eptr; /* pointer */ }; A structure containing a member that is a pointer to the same structure type is referred to as a self-referential structure 6

The structure tag name is optional struct char firstname[ 20 ]; char lastname[ 20 ]; int age; char gender; double hourlysalary; } Ali; If a structure definition does not contain a structure tag name, variables of the structure type may be declared only in the structure definition not in a separate declaration 7

Structure definitions do not reserve any space in memory; rather, each definition creates a new data type that is used to define variables sizeof(struct ) = sum of sizeof(members) + alignment padding (Processor- and compiler-specific) struct employee char firstname[ 20 ]; char lastname[ 20 ]; int age; char gender; double hourlysalary; }; struct employee Ali, emp[10]; printf("%d", sizeof(ali)); printf("%d", sizeof(emp)); printf("%d", sizeof(struct employee)); 8

struct char a[3]; short int b; long int c; char d[3]; }; it's much, much easier on the processor if the compiler arranges it like this: most compilers will pad the structure (as if with extra, invisible fields) like this: 9

Individual members of a struct variable may be accessed using the structure member operator (the dot, "."): myemp.firstname ; employee. firstname; // Error Or, if a pointer to the struct has been declared and initialized employee *emp = &myemp ; by using the structure pointer operator : emp firstname; // arrow operator which could also be written as: (* emp).firstname; 10

struct identity sharifc40153[80] = Omid", "Jafarinezhad", 14, 9140153, 20, "Samad", "Shekarestani", 90, 2222222, 20} ; strcpy(sharifc40153[2].firstname, "Khaje Nezam"); strcpy(sharifc40153[2].lastname, "Shekarestani"); sharifc40153[2]. age = 100; sharifc40153[2]. person.id = 11111111; sharifc40153[2]. person. gpa = 20; FirstName LastName age id person gpa students[0] omid Jafarinezhad 14 9140153 20 Students[1] Samad Shekarestani 90 2222222 20 students[2] Khaje Nezam Shekarestani 100 11111111 20 students[3] 11

#define NFRIENDS 10 struct Date unsigned year; unsigned month; unsigned day; }; struct Friend char FirstName[30]; char LastName[30]; struct Date Birthday; }; bool check_birthday(struct Date today, struct Date myfriend) if ((today.month == myfriend.month) && (today.day == myfriend.day)) return (true); return (false); } int main() struct Friend friends[nfriends]; struct Date today = 2017, 11, 25}; //... for (i = 0; i < NFRIENDS; i++) if(check_birthday(today, friends[i].birthday)) printf ("%s %s\n", friends[i].firstname, oj.lastname) ; } // 12

Notice that bit field members of structures are accessed exactly as any other structure member struct Flags int unsigned int unsigned int } foo; f1:3; f2:1; f3:2; f1 f2 f3 1 1 0 1 1 0 8 bit 8 bit 8 bit foo.f1 = -2; foo.f2 = 1; foo.f3 = 2; Padded to be an integral number of words Placement is compiler-specific 13

Date today; today = create_date1(9, 4, 2008); create_date2(&today, 9, 4, 2008); Date create_date1(int month, int day, int year) Date d; d.month = month; d.day = day; d.year = year; return (d); } 14 void create_date2(date *d, int month, int day, int year) d->month = month; d->day = day; d->year = year; }

typedef struct char firstname[ 20 ]; char lastname[ 20 ]; int age; char gender; double hourlysalary; } employee; /* The "alias" employee Ali; /* Create a struct variable */ 15

Structures may not be compared using operators == and!= struct a int a; int b; }; struct a b, c; b.a = 10; b.b = 30; c = b; if(c == b) // Error 16

Enumeration is a user-defined data type. It is defined using the keyword enum and the syntax is: enum tag_name name_0,, name_n} ; The tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n. As an example, the statement: enum colors red, yellow, green } ; creates three constants. red is assigned the value 0, yellow is assigned 1 and green is assigned 2 17

#include <stdio.h> int main( ) int March[5][7]=0,0,1,2,3,4,5}, 6,7,8,9,10,11,12}, 13,14,15,16,17,18,19}, 20,21,22,23,24,25,26}, 27,28,29,30,31,0,0}}; enum days Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; enum week week_one, week_two, week_three, week_four, week_five}; } printf ("Monday the third week of March is March %d\n", March [week_three] [Monday] ); 18

Values in an enum start with 0, unless specified otherwise, and are incremented by 1 The identifiers in an enumeration must be unique Multiple members of an enumeration can have the same constant value Assigning a value to an enumeration constant after it has been defined is a syntax error Use only uppercase letters enumeration constant names. This makes these constants stand out in a program and reminds you that enumeration constants are not variables 19

enum months JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; enum months month; /* initialize array of pointers */ const char *monthname[] = "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", November", "December"}; for (month = JAN; month <= DEC; month++ ) printf( "%2d%11s\n", month, monthname[month] ); } 20

A union is a derived data type like a structure with members that share the same storage space For different situations in a program, some variables may not be relevant, but other variables are so a union shares the space instead of wasting storage on variables that are not being used The members of a union can be of any data type The number of bytes used to store a union must be at least enough to hold the largest member Only one member, and thus one data type, can be referenced at a time 21

union mydataunion int i; char c; float f; } u1, u2; union mydataunion u3; f i c u1.i = 4; u1.c = a ; u2.i = 0xDEADBEEF; 22

In a declaration, a union may be initialized with a value of the same type as the first union member union a int c; // OK char b[4]; }; union a test; test.c = 10; printf("%d", test.c); 23

A union value doesn t "know" which case it contains union AnElt int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = a ; elt2.i = 0xDEADBEEF; How should your program keep track whether elt1, elt2 hold an int or a char? Basic answer: Another variable holds that info if (elt1 currently has a char) 24

Tag every value with its case enum Union_Tag IS_INT, IS_CHAR}; struct TaggedUnion enum Union_Tag tag; union int i; char c; } data; }; 25

26

class GradeBook public: void setcoursename( string name ) coursename = name; } string getcoursename() return coursename; } void displaymessage() cout << "Welcome to the grade book for\n" << getcoursename() << "!" << endl; } private: string coursename; }; 27

GradeBook book( MyBook ); int number; cin >> number; cout << Book << book.getcoursename()<< has << number << pages << endl; 28