Everything Else C Programming and Software Tools. N.C. State Department of Computer Science

Similar documents
A Fast Review of C Essentials Part I

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

Advanced Pointer & Data Storage

Type Checking. Prof. James L. Frankel Harvard University

Fundamental of Programming (C)

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Functions in C C Programming and Software Tools

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Topic 6: A Quick Intro To C

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

BLM2031 Structured Programming. Zeyneb KURT

CS Programming In C

Dept. of Computer and Information Science (IDA) Linköpings universitet Sweden

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

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

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS 61C: Great Ideas in Computer Architecture Introduction to C

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

EL6483: Brief Overview of C Programming Language

Creating a C++ Program

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

Motivation was to facilitate development of systems software, especially OS development.

C Programming Review CSC 4320/6320

Tokens, Expressions and Control Structures

Functions. Cedric Saule

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Motivation was to facilitate development of systems software, especially OS development.

Contents Lecture 3. C Preprocessor, Chapter 11 Declarations, Chapter 8. Jonas Skeppstedt Lecture / 44

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

Computer Systems Principles. C Pointers

C Language Advanced Concepts. Microcomputer Architecture and Interfacing Colorado School of Mines Professor William Hoff

CS201: Lab #4 Writing a Dynamic Storage Allocator

5.Coding for 64-Bit Programs

COMP322 - Introduction to C++

Object-Oriented Programming

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

G52CPP C++ Programming Lecture 8. Dr Jason Atkin

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

Chapter 2. Procedural Programming

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

Simple Data Types in C. Alan L. Cox

Kurt Schmidt. October 30, 2018

CMPE-013/L. Introduction to C Programming

6.096 Introduction to C++ January (IAP) 2009

1. We have a code sequence that is potentially executed twice.

Input And Output of C++

COMP 2355 Introduction to Systems Programming

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Introduction to Information Security. Secure Coding Sang Kil Cha

Approximately a Final Exam CPSC 206

EL2310 Scientific Programming

Computer Programming: Skills & Concepts (CP) Strings

printf( Please enter another number: ); scanf( %d, &num2);

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Exercise Session 2 Systems Programming and Computer Architecture

Fundamental of Programming (C)

JTSK Programming in C II C-Lab II. Lecture 3 & 4

Chapter 14 - Advanced C Topics

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

Binghamton University. CS-211 Fall Variable Scope

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

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

Binghamton University. CS-211 Fall Variable Scope

C Language, Token, Keywords, Constant, variable

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

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

Chapter-8 DATA TYPES. Introduction. Variable:

Programming in C - Part 2

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

XSEDE Scholars Program Introduction to C Programming. John Lockman III June 7 th, 2012

Lectures 5-6: Introduction to C

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

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CS61, Fall 2012 Section 2 Notes

Compiling and Running a C Program in Unix

CS349/SE382 A1 C Programming Tutorial

CS201 - Introduction to Programming Glossary By

C: How to Program. Week /Mar/05

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Chapter 1 & 2 Introduction to C Language

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

An Ungentle Introduction to C

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

QUIZ. What are 3 differences between C and C++ const variables?

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Exercise Session 2 Simon Gerber

CSE 333 Midterm Exam Sample Solution 7/28/14

C Syntax Out: 15 September, 1995

Page 1. Agenda. Programming Languages. C Compilation Process

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Preprocessor Directives

Lectures 5-6: Introduction to C

Review of the C Programming Language for Principles of Operating Systems

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Transcription:

Everything Else C Programming and Software Tools N.C. State Department of Computer Science

BOOLEANS CSC230: C and Software Tools NC State University Computer Science Faculty 2

Booleans In C99, bools are included! Sort of! _Bool b = 1; Why so ugly? To not conflict with existing code. But if you want nice bools plus true and false, ask for them by name: #include <stdbool.h> bool b = true; bool c = false; CSC230: C and Software Tools NC State University Computer Science Faculty 3

stdbool.h #ifndef _STDBOOL_H #define _STDBOOL_H #ifndef cplusplus #define bool _Bool #define true 1 #define false 0 #else /* cplusplus */ /* Supporting <stdbool.h> in C++ is a GCC extension. */ #define _Bool bool #define bool bool #define false false #define true true #endif /* cplusplus */ /* Signal that all the definitions are present. */ #define bool_true_false_are_defined 1 #endif /* stdbool.h */ CSC230: C and Software Tools NC State University Computer Science Faculty 4

CONST & CONST POINTERS CSC230: C and Software Tools NC State University Computer Science Faculty 5

Const pointer - summary Commonly used in argument/return types: char *strcpy(char *dest, const char *src); CSC230: C and Software Tools NC State University Computer Science Faculty 6

The const Keyword... Indicates to the compiler that a value should not change during program execution should be initialized, but not changed const int twopowfive = 32; const float pi = 3.14159; twopowfiv = 64; /* ERROR */ pi = 6.3; /* ERROR */ CSC230: C and Software Tools NC State Computer Science Faculty 7

... (cont d) Is this better than macros? #define TWOPOWFIV 32 #define PI 3.14159 Derived types can be const also struct pet { char *name; unsigned short weight; unsigned char age; unsigned char type; }; const struct pet mypet = { Fluffy, 30, 5, DOG }; CSC230: C and Software Tools NC State Computer Science Faculty 8

const and Pointers... Is it the pointer that cannot be changed, or the thing it points at? Changeable pointer to changeable character: char * cp = &c; *cp++ = A ; /* no problems */ Constant pointer to changeable character char * const cp = &c; *cp = Q ; /* No problems */ cp = &d ; /* ERROR, changes pointer */ CSC230: C and Software Tools NC State Computer Science Faculty 9

... (cont'd) Changeable pointer to constant character const char * cp = &c; *cp = Z ; /* ERROR, changes value * pointed to */ c = Z ; /* But this is OK! */ cp = &d; /* No problems */ Constant pointer to constant character const char * const cp = &c; *cp++ = Z ; /* ERROR, changes both */ Considered good practice; use whenever possible (particularly pointers passed to functions) Commonly used in argument/return types: char *strcpy(char *dest, const char *src); CSC230: C and Software Tools NC State Computer Science Faculty 10

ENUMS: THE ENUMERATED DATA TYPE CSC230: C and Software Tools NC State University Computer Science Faculty 11

Enumerated Data Type Use for variables with small set of possible values, where actual encoding of value is unimportant enum colors {red, blue, green, white, black}; enum colors mycolor; mycolor = blue;... if ((mycolor == blue) (mycolor == green)) printf("cool color\n"); CSC230: C and Software Tools NC State Computer Science Faculty 12

(cont d) Don t compare variables of different enumerated types - results not what you expect! enum {blue, red, green, white, black} primarycolor; enum {black, brown, orange, yellow} halloweencolor; primarycolor = black; halloweencolor = black; if (primarycolor == halloweencolor) printf("same color\n"); What will print? Although you can interpret enumerated data types as integers, I don t recommend it CSC230: C and Software Tools NC State Computer Science Faculty 13

(cont d) Compared to macros? #define BLUE 0 #define RED 1 #define GREEN 2 #define WHITE 3 #define BLACK 4 int primarycolor; primarycolor = RED; if (primarycolor == RED) GNOME: If you have a list of possible values for a variable, do not use macros for them; use an enum instead and give it a type name CSC230: C and Software Tools NC State Computer Science Faculty 14

TYPEDEF CSC230: C and Software Tools NC State University Computer Science Faculty 15

Typedef Make an alias for a type: typedef unsigned char byte; typedef int* int_pointer; byte x = 5; int q = 12; int_pointer pq = &q; CSC230: C and Software Tools NC State University Computer Science Faculty 16

Typedef structs (1) Commonly used with structs: typedef struct { char name[64]; int age; } Person; Person bob = { Bob, 65}; struct Person sue; No such type! CSC230: C and Software Tools NC State University Computer Science Faculty 17

Typedef structs (2) Sometimes you need it to be a named struct too, though typedef struct Node { int id; struct Node *next; } Node; typedef struct Node { int id; Node *next; } Node; Node is undefined at this time! CSC230: C and Software Tools NC State University Computer Science Faculty 18

Typedef structs (3) It s common to typedef a pointer to a struct to make a class-like thingy : struct Person { char name[64]; int age; }; typedef struct Person* Person; Person create_person(char* name, int age) { } Person bob = create_person( Bob,65); CSC230: C and Software Tools NC State University Computer Science Faculty 19

Typedef arrays? Even arrays can be typedefs typedef int values[20]; values tbl1, tbl2; /* two arrays, each with * 20 ints */ typedefs help make programs portable to retarget a program for a different architecture, just redefine the typedefs and recompile Usually, typedefs are collected in a header file that is #include d in all source code modules CSC230: C and Software Tools NC State Computer Science Faculty 20

UNIONS CSC230: C and Software Tools NC State University Computer Science Faculty 21

The union Statement Defined like a struct, but only stores exactly one of the named members motivation: use less memory Nothing in the union tells you which member is stored there! usually, another variable indicates what is stored in the union CSC230: C and Software Tools NC State Computer Science Faculty 22

union Example /* animal can have only one of the following */ union properties { unsigned short speed_of_flight; // bird bool is_freshwater; // fish enum {VERY, SOME, NONE} hairiness; // mammal }; struct { unsigned char type; char * name; union properties info; } animals[10]; animals[0].type = MAMMAL; animals[0].name = "Polar Bear"; animals[0].info.hairiness = VERY; CSC230: C and Software Tools NC State Computer Science Faculty 23

Unions can decompose types (Like a pointer cast without the pointer, or the cast) union flippable_int { unsigned char bytes[4]; int value; }; value = 100000 (0x000186a0) bytes = {a0,86,01,00} value = -1601830656 (0xa0860100) bytes = {00,01,86,a0} int main() { union flippable_int x = {.value = 100000 }; printf("value = %d (0x%08x)\n", x.value, x.value); printf("bytes = {%02x,%02x,%02x,%02x}\n", x.bytes[0], x.bytes[1], x.bytes[2], x.bytes[3]); // convert to big endian unsigned char t; t = x.bytes[0]; x.bytes[0] = x.bytes[3]; x.bytes[3] = t; t = x.bytes[1]; x.bytes[1] = x.bytes[2]; x.bytes[2] = t; printf("value = %d (0x%08x)\n", x.value, x.value); printf("bytes = {%02x,%02x,%02x,%02x}\n", x.bytes[0], x.bytes[1], x.bytes[2], x.bytes[3]); } CSC230: C and Software Tools NC State University Computer Science Faculty 24

VARIABLE NUMBER OF ARGUMENTS CSC230: C and Software Tools NC State University Computer Science Faculty 25

Functions with a Variable Number of Arguments... Example: printf(char *fmt, ) the first argument (char *fmt, the named argument) indicates how many, and what type, of unnamed arguments to expect the... (the unnamed arguments) stands for an arbitrary list of arguments provided by the calling program CSC230: C and Software Tools NC State Computer Science Faculty 26

(cont d) Requires macros defined in <stdarg.h> In function f(): 1. Declare a variable of type va_list 2. Call va_start; returns pointer to the first unnamed argument 3. Call va_arg to return pointer to each successive unnamed argument 4. Call va_end to end processing CSC230: C and Software Tools NC State Computer Science Faculty 27

(cont d) How many unnamed parameters? this has to be indicated by the named parameter What are types of unnamed parameters? either this is fixed (implicit), or the named parameter must explicitly indicate example: the printf() format specifier CSC230: C and Software Tools NC State Computer Science Faculty 28

Example... A function sumup(num, ) which returns the sum of a list of num arguments, all of type int Calling sumup(): #include <stdio.h> #include <stdarg.h> int sumup(int, ); int main(void) { int i = 295, j = 3, k = 450, res; res = sumup(3, i, j, k); } Number of unnamed arguments List of unnamed arguments CSC230: C and Software Tools NC State Computer Science Faculty 29

(cont d) Definition of sumup(): int sumup(int num, ) { int sum; va_list ap; va_start(ap, num); sum = 0; for(int i = 0; i < num; i++) sum += va_arg(ap, int); Declare pointer to arguments Makes ap point to first unnamed argument } va_end(ap); return sum; Read unnamed arguments, all of type int Clean up before exiting CSC230: C and Software Tools NC State Computer Science Faculty 30

Another Example... Function sumup(char *fmt, ), where fmt specifies type and number of unnamed arguments one character per unnamed argument types = i (int), d (double), and c (char) Ex.: if fmt[] equals iddic there are 5 unnamed arguments, first and fourth are type int, second and third are type double, fifth is type char float sumup(char *fmt, ); float res; res = sumup( cid, (char) Q, 2500, 3.141); CSC230: C and Software Tools NC State Computer Science Faculty 31

(cont d) float sumup(char *fmt, ) { int i; float sum = 0, d; char c; va_list ap; va_start(ap, fmt); for(; *fmt!= \0 ; fmt++) if (*fmt == c ) sum += va_arg(ap, char)); else if (*fmt == i ) sum += va_arg(ap, int)); else if (*fmt == d ) sum += va_arg(ap, double)); va_end(ap); return sum; } CSC230: C and Software Tools NC State Computer Science Faculty 32

ENVIRONMENT VARIABLES CSC230: C and Software Tools NC State University Computer Science Faculty 33

Environmental Variables A way for a user to customize the execution environment of programs Ex.: cmd> echo $HOME /home/jerry cmd> HOME=/home/linda cmd> echo $HOME /home/linda Common environment variables: TERM MAIL SHELL GROUP USER LANG PATH EDITOR PRINTER HOME CSC230: C and Software Tools NC State Computer Science Faculty 34

Reading / Writing E.V. s in C Read using getenv() (#include <stdlib.h>) char *string = getenv( HOME ); printf( $HOME=%s\n, string); And setenv() if you want to change them setenv( HOME, "/home/new", 1); CSC230: C and Software Tools NC State Computer Science Faculty 35

BIT FIELDS CSC230: C and Software Tools NC State University Computer Science Faculty 36

8. Bit Fields in C Way to pack bits into a single word; useful? Bit fields of a word are defined like members of a structure CSC230: C and Software Tools NC State Computer Science Faculty 37

Bit Fields Example... (http://www.cs.cf.ac.uk/dave/c/) Frequently devices and OS communicate by means of a single word struct Disk_register { unsigned ready:1; unsigned error_occurred:1; unsigned disk_spinning:1; unsigned write_protect:1; unsigned head_loaded:1; unsigned error_code:8; unsigned track:9; unsigned sector:5; unsigned command:5; }; CSC230: C and Software Tools NC State Computer Science Faculty 38

...(cont d) struct Disk_register * dr = (struct Disk_register * ) MEMADDR; /* Define sector and track to start read */ dr->sector = new_sector; dr->track = new_track; dr->command = READ; /* ready will be true when done, else wait */ while (! dr->ready ) ; if (dr->error_occurred) /* check for errors */ { switch (dr->error_code)... } CSC230: C and Software Tools NC State Computer Science Faculty 39

Warnings About Bit Fields Recommendation: always make bit fields unsigned # of bits determines maximum value Restrictions 1. no arrays of bit fields Danger: files written using bit-fields are nonportable! order in which bit-fields stored within a word is system dependent CSC230: C and Software Tools NC State Computer Science Faculty 40

Any Questions? CSC230 - C and Software Tools NC State University Computer Science Faculty 41