The programming language C. sws1 1



Similar documents
How To Write Portable Programs In C

Informatica e Sistemi in Tempo Reale

Sources: On the Web: Slides will be available on:

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Number Representation

DNA Data and Program Representation. Alexandre David

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

Useful Number Systems

Computer Science 281 Binary and Hexadecimal Review

Base Conversion written by Cathy Saxton

Chapter 7D The Java Virtual Machine

1 The Java Virtual Machine

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Lecture 7: Programming for the Arduino

Ch. 10 Software Development. (Computer Programming)

Memory Systems. Static Random Access Memory (SRAM) Cell

Pemrograman Dasar. Basic Elements Of Java

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

1/20/2016 INTRODUCTION

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

CSI 333 Lecture 1 Number Systems

The C Programming Language course syllabus associate level

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

Chapter 4: Computer Codes

Caml Virtual Machine File & data formats Document version: 1.4

Numbering Systems. InThisAppendix...

Motorola 8- and 16-bit Embedded Application Binary Interface (M8/16EABI)

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

SECTION C [short essay] [Not to exceed 120 words, Answer any SIX questions. Each question carries FOUR marks] 6 x 4=24 marks

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Beyond the Mouse A Short Course on Programming

So far we have considered only numeric processing, i.e. processing of numeric data represented

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping

Section 1.4 Place Value Systems of Numeration in Other Bases

Keil C51 Cross Compiler

COS 217: Introduction to Programming Systems

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Subject knowledge requirements for entry into computer science teacher training. Expert group s recommendations

Lecture 22: C Programming 4 Embedded Systems

First Bytes Programming Lab 2

Solution for Homework 2

HOMEWORK # 2 SOLUTIO

CDA 3200 Digital Systems. Instructor: Dr. Janusz Zalewski Developed by: Dr. Dahai Guo Spring 2012

Programming Languages CIS 443

Memory is implemented as an array of electronic switches

FEEG Applied Programming 5 - Tutorial Session

Jonathan Worthington Scarborough Linux User Group

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

Machine Architecture and Number Systems. Major Computer Components. Schematic Diagram of a Computer. The CPU. The Bus. Main Memory.

Chapter 1. Dr. Chris Irwin Davis Phone: (972) Office: ECSS CS-4337 Organization of Programming Languages

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Lexical Analysis and Scanning. Honors Compilers Feb 5 th 2001 Robert Dewar

Top 10 Bug-Killing Coding Standard Rules

Instruction Set Architecture (ISA)

C++ Language Tutorial

Introduction to Python

Copyright 2012 Pearson Education, Inc. Chapter 1 INTRODUCTION TO COMPUTING AND ENGINEERING PROBLEM SOLVING

Fundamentals of Programming

The Answer to the 14 Most Frequently Asked Modbus Questions

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

2011, The McGraw-Hill Companies, Inc. Chapter 3

The string of digits in the binary number system represents the quantity

Introduction to Scientific Computing Part II: C and C++ C. David Sherrill School of Chemistry and Biochemistry Georgia Institute of Technology

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Compilers. Introduction to Compilers. Lecture 1. Spring term. Mick O Donnell: michael.odonnell@uam.es Alfonso Ortega: alfonso.ortega@uam.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Lecture 7: Machine-Level Programming I: Basics Mohamed Zahran (aka Z)

I PUC - Computer Science. Practical s Syllabus. Contents

Computer Science 217

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages

Programming languages C

This section describes how LabVIEW stores data in memory for controls, indicators, wires, and other objects.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Computers. Hardware. The Central Processing Unit (CPU) CMPT 125: Lecture 1: Understanding the Computer

Systems I: Computer Organization and Architecture

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

C++ Programming Language

CS 106 Introduction to Computer Science I

Operating System Overview. Otto J. Anshus

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

Programming the Arduino

1. Convert the following base 10 numbers into 8-bit 2 s complement notation 0, -1, -12

Interpreters and virtual machines. Interpreters. Interpreters. Why interpreters? Tree-based interpreters. Text-based interpreters

Computer Programming I

ECE 0142 Computer Organization. Lecture 3 Floating Point Representations

Semantic Analysis: Types and Type Checking

An Introduction to Computer Science and Computer Organization Comp 150 Fall 2008

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Object Oriented Software Design

Compiler Construction

CS 40 Computing for the Web

CS101 Lecture 11: Number Systems and Binary Numbers. Aaron Stevens 14 February 2011

CSC230 Getting Starting in C. Tyler Bletsch

Transcription:

The programming language C sws1 1

The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan & Ritchie) C ANSI C aka C90 C99 newer ISO standard in 1999 C11 most recent ISO standard of 2011 Basis for C++, Objective C,... and many other languages NB C++ is not a superset of C Many other variants, eg MISRA C for safety-critical applications in car industry sws1 2

The programming language C C is very powerful, and can be very efficient, because it gives raw access to the underlying platform (CPU and memory) Downside: C provides less help to the programmer to stay out of trouble than other languages. C is very liberal (eg in its type system) and does not prevent the programmer from questionable practices, which can make it harder to debug programs. [For example, see the program silly_bool_argument.c] sws1 3

syntax & semantics A programming language definition consists of Syntax The spelling and grammar rules, which say what legal - or syntactically correct - program texts are. Syntax is usually defined using a grammar, typing rules, and scoping rules Semantics The meaning of legal programs. Much harder to define! The semantics of some syntactically correct programs may be left undefined (but it is better not do this!) sws1 4

C compilation in more detail As first step, the C preprocessor will add and remove code from your source file, eg using #include directives and expanding macros The compiler then translates programs into object code Object code is almost machine code Most compilers can also output assembly code, a human readable form of this The linker takes several pieces of object code (incl. some of the standard libraries) and joins them into one executable which contains machine code Executables also called binaries By default gcc will compile and link sws1 5

What does a C compiler have to do? 1. represent all data types as bytes 2. decide where pieces of data are stored (memory management) 3. translate all operations into the basic instruction set of the CPU this includes translating higher-level control structures, such as if then else, switch statements, for loops, into jumps (goto) 4. provide some hooks so that at runtime the CPU and OS can handle function calls NB function calls have to be handled at runtime, when the compiler is no longer around, so this has to be handled by CPU and OS sws1 6

Memory abstraction (1): how data is represented C provides some data types, and programmer can use these without having to know how they are represented - to some degree. eg. in C we can write character string a floating point number 1.345 Hello World array of int s {1,2,3,4,5} complex number 1.0 + 3.0 * I sws1 7

Memory abstraction (2): where data is stored The programmer also do not need to know where the data is stored (aka allocated) - again to some degree. This is called memory management. At runtime, an int x could be stored in a register on the CPU in the CPU cache in RAM on hard disk Compiler will make some decisions here, but it s up to the operating system and CPU to do most of this work at runtime sws1 8

Where is data allocated? & We can find out where some data is allocated using the & operation. Suppose we have a variable int x = 12; Then &x is the memory address where the value of x is stored, aka a pointer to x 12 &x Much more on pointers later! sws1 9

Where is data allocated? pointers char x; int i; short s; char y; printf("x is allocated at %p \n", &x); printf("i is allocated at %p \n", &i); printf("s is allocated at %p \n", &s); printf("y is allocated at %p \n", &y); // Here %p is used to print pointer values sws1 10

C data types and their representation sws1 11

Computer memory The memory can be seen as a sequence of bytes Actually, it is a sequence are n-bytes words where n=1, 2,4,8 on 8,16, 32, 64 bit architecture All data is in the end just bytes everything is represented as bytes; not just data, also code different data can have the same representation as bytes hence the same byte can have different interpretations, depending on the context the same piece of data may even have different representations sws1 12

char The simplest data type in C is char. A char is always a byte. The type char was traditionally used for ASCII characters, so char values can be written as numbers or as characters, e.g. char c = 2 ; char d = 2; char e = 50; QUIZ: which of the variables above will be equal? c and e, as they both have value 50: the character 2 is represented as its ASCII code 50 sws1 13

other integral types C provides several other integral types, of different sizes short or short int usually 2 bytes int usually 2 or 4 bytes long or long int 4 or 8 bytes long long 8 bytes or longer The exact sizes can vary depending on the platform! You can use sizeof()to find out the sizes of types, eg sizeof(long) or sizeof(x) Integral values can be written in decimal, hexadecimal (using 0x) or octal notation (using 0), where 0 is zero, not O eg 255 is 0xFF (hexadecimal) or 0177777 (octal) sws1 14

Printing values in different notations The procedure printf can print numeric values in different notations. int j = 15; printf( The value of j is %i \n, j); printf( In octal notation: %o \n, j); printf( In hexadecimal notation: %x \n, j); printf( Idem with capitals: %X \n, j); Check websites such as cppreference.com for details. See course webpage for more links. sws1 15

floating point types C also provides several floating point types, of different sizes float double long double Again, sizes vary depending on the platform. The floating point types will probably not be used in this course. sws1 16

signed vs unsigned Numeric types have signed and unsigned versions The default is signed - except possibly for char For example signed char can have values -128... 127 unsigned char can have values 0... 255 In these slides, I will assume that char is by default a signed char sws1 17

register Originally, C had a keyword register register int i; This would tell the compiler to store this value in a CPU register rather than in main memory. The motivation for this would be that this variable it is used frequently. NB you should never ever use this! Compilers are much better than you are at figuring out which data is best stored in CPU registers. sws1 18

stdint.h Because the bit-size (or width) of standard types such as int and long can vary, there are standard libraries that define types with guaranteed sizes. Eg stdint.h defines uint16_t for unsigned 16 bit integers sws1 19

implicit type conversions Values of numeric type will automatically be converted to wider types when necessary. Eg char converts to int, int to float, float to double char c = 1; int i = 2; float f = 3.1415; double d = i * f; // i converted to float, then // i * f converted to double long g = (c*i)+i; // c converted to an int // then result to a long What happens if c*i overflows as 32-bit int, but not as 64-bit long? My guess is that it s platform-specific, but maybe the C spec says otherwise? sws1 20

explicit type casts You can cast a value to another type int i = 23456; char c = (char) i; // drops the higher order bits float f = 12.345; i = (int) f; // drops the fractional part Such casts can loose precision, but the cast make this explicit. Question: can c have a negative value after the cast above? It may have, if the lower 8 bits of 23456 happen to represent a negative number, for the representations of int and char (incl. negative chars) used. So casts cannot only loose precision, but also change the meaning sws1 21

some implicit conversion can also be dangerous int i = 23456; char c = i; unsigned char s = c; the compiler might (should?) complain that we loose bits what if c is negative? Is this legal C code? Is the semantics clear? C compilers do not always warn about dangerous implicit conversions which may loose bits or change values! Conversions between signed and unsigned types do not always give intuitive results. Of course, a good programmer will steer clear of such implicit conversions. sws1 22

Quiz: signed vs unsigned Conversions between signed and unsigned data types do not always behave intuitively unsigned char x = 128; signed char y = x; // what will value of y be? Moral of the story: mixing signed and unsigned data types in one program is asking for trouble sws1 23

Representation: two s complement Most platforms represent negative numbers using the two s complement method. Here the most signification bit represents a large negative number (2 n ) -128 64 32 16 8 4 2 1 So -128 is represented as 1000 0000-120 as 1000 0100 and the largest possible signed byte value, 127, as 0111 1111 sws1 24

Representation: big endian vs little endian Integral values that span multiple bytes can be represented in two ways big endian : most significant byte first little endian : least significant byte first (ie backwards) For example, a long long x = 1 is represented as 00 00 00 01 big endian 01 00 00 00 litte endian Some operations are easier to implement for a big endian representation, others for little endian. Little endian may seems strange, but has the advantage that types of different lengths can be handled more uniformly: eg litte endian, an int 1 would be represented as 01 00 sws1 25