C A short introduction

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

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

The C Programming Language course syllabus associate level

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

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Moving from CS 61A Scheme to CS 61B 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)

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

5 Arrays and Pointers

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

Objective-C Tutorial

Pemrograman Dasar. Basic Elements Of Java

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

VB.NET Programming Fundamentals

Chapter 13 Storage classes

1 Abstract Data Types Information Hiding

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

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

arrays C Programming Language - Arrays

Simple C Programs. Goals for this Lecture. Help you learn about:

Chapter 2: Elements of Java

C++ Language Tutorial

The programming language C. sws1 1

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Informatica e Sistemi in Tempo Reale

Chapter One Introduction to Programming

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

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

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Chapter 5 Names, Bindings, Type Checking, and Scopes

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Computer Programming C++ Classes and Objects 15 th Lecture

C++ Programming Language

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

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

The C Programming Language

Object Oriented Software Design II

C Programming Tutorial

CP Lab 2: Writing programs for simple arithmetic problems

JavaScript: Control Statements I

Tutorial on C Language Programming

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Building Embedded Systems

Computer Programming Tutorial

Illustration 1: Diagram of program function and data flow

Answers to Review Questions Chapter 7

Install Java Development Kit (JDK) 1.8

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Chapter 13 - The Preprocessor

Introduction to Python

Arrays in Java. Working with Arrays

Variables, Constants, and Data Types

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

C++ INTERVIEW QUESTIONS

PL / SQL Basics. Chapter 3

ELEC3730 Embedded Systems Lecture 1: Introduction and C Essentials

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

An Incomplete C++ Primer. University of Wyoming MA 5310

Beyond the Mouse A Short Course on Programming

Semantic Analysis: Types and Type Checking

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

In this Chapter you ll learn:

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

Object Oriented Software Design

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

Glossary of Object Oriented Terms

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Lecture 5: Java Fundamentals III

El Dorado Union High School District Educational Services

Chapter 3. Input and output. 3.1 The System class

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Object Oriented Software Design

Java (12 Weeks) Introduction to Java Programming Language

Java Crash Course Part I

MISRA-C:2012 Standards Model Summary for C / C++

FEEG Applied Programming 5 - Tutorial Session

CS 106 Introduction to Computer Science I

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

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Moving from C++ to VBA

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

Java Interview Questions and Answers

Parallel and Distributed Computing Programming Assignment 1

Programming Microcontrollers in C

Chapter 2 Elementary Programming

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

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

3 Data Properties and Validation Rules

/* File: blkcopy.c. size_t n

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

COS 217: Introduction to Programming Systems

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

13 Classes & Objects with Constructors/Destructors

Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362

Programming in Java Course Technology, a part of Cengage Learning.

Transcription:

About these lectures C A short introduction Stefan Johansson Department of Computing Science Umeå University Objectives Give a short introduction to C and the C programming environment in Linux/Unix Go into depth of C Pointers, arrays, structures, preprocessing Introduce Make and makefiles Modeling and Simulation: C intro 2 Recommended readings Books Hanly and Koffman. Problem Solving and Program Design in C. 6th Ed., 2010. ISBN 978-0-321-60151-3. Hanly and Koffman. C Program Design for Engineers. 2nd Ed., 2001 Web-based tutorials and reference pages C Tutorial http://www.cprogramming.com/tutorial.html#ctutorial The GNU C library http://www.gnu.org/s/libc/manual/html_node/index.html Numerical Recipes in C http://www.nrbook.com/a/bookcpdf.php Local The man-pages on Linux/Unix is an excellent reference manual. Just type man followed by the C function name (available in a standard C library) Modeling and Simulation: C intro 3 A C program Source files (extension.c) The code... Header files (.h) Function prototypes, user-defined types, and preprocessing directives Libraries (.a or.so;.lib or.dll in MS Windows) A library is a collection of functions and symbols Every C implementation includes a set of standard libraries, e.g., for I/O- and math-operations Each library has a header file associated to it. Must be included to get access to the functions in the library Modeling and Simulation: C intro 4

Compilation Compile with GNU C compiler gcc > gcc myprogram.c What does gcc do? Preprocessing Compilation Assembly Linking Executable output is by default called a.out Compilation (cont.) Options (see gcc s man-pages for more options) -o file Place output in file file -Wall Issue the most common warnings (recommended) -pedantic Issue all the warnings demanded by strict ISO C -O2 Optimize -O3 Optimize even more -g Stores information for the debugger Modeling and Simulation: C intro 5 Modeling and Simulation: C intro 6 The source file Preprocessor directives Preprocessor directive Function header Comment A comment begin with /* and end with */ End of main function #include <stdio.h> int main(void) { /* Include function body here */ } return (0); Each executable statement must end with a semi-colon (;) Begin with # Instructions to the C preprocessor how to modify the C source before the code is compiled Common directives are #include and #define Modeling and Simulation: C intro 7 Modeling and Simulation: C intro 8

Preprocessor directives (cont.) Identifiers Examples #include <stdio.h> #include myheader.h #define PI 3.14 By convention, written in all capital letters Include the standard header file stdio.h Include the user written header file myheader.h Exchange every occurence of PI in the code with 3.14 Names of functions, variables, etc. Uppercase and lowercase letters matters Valid user-defined identifiers Can only consist of letters, digits, and underscores Cannot begin with a digit Reserved words cannot be used Avoid using more than 31 characters Use meaningful names! Modeling and Simulation: C intro 9 Modeling and Simulation: C intro 10 Fundamental data types Integral types short, int, long, and long long Exist also in unsigned versions, e.g., uint (unsigned int) char Used for representing one character Floating-point types float, double, and long double Variables A variable must be declared before it can be referenced (used) A variable is deallocated when the function returns It s good practice to declare all variables in the beginning of a function, but it is not necessary Variables are not initialized to zero Modeling and Simulation: C intro 11 Modeling and Simulation: C intro 12

Variables (cont.) Variables (cont.) Syntax data_type variable_list; Examples int nr_pigs; double weight, tot_weight; Variables can be initialized at declaration int nr_pigs = 10; Good practice to initialize all variables Constants are declared using const const int a_constant_var; Variables declared with static are not deallocated until the program terminates Used to preserve a value between calls to a function Should normaly be avoided Modeling and Simulation: C intro 13 Modeling and Simulation: C intro 14 Global variables A variable declared outside of a function is called a global variable A global variable can be referenced by all subsequent functions A local variable with the same name will hide the global Global variables should be avoided! Type casting Conversion of a variable of one data type to another data type. Must be done for assignment between variables of different types Automatic type casting is done by the compiler for standard numeric data types Modeling and Simulation: C intro 15 Modeling and Simulation: C intro 16

Automatic type casting double int int a; double b = 1.524; a = b; a = 1 int double int a = 1; double b; b = a; b = 1.0 Automatic type casting int k = 5, m = 4, n; double x = 1.5, y = 2.1, z; Mixed expression k + x 6.5 int double z = k / m; z = 1.0 (1.25) double int n = x y; n = 3 (3.15) Modeling and Simulation: C intro 17 Modeling and Simulation: C intro 18 Explicit type casting Syntax (new_type) expression Examples z = (double)(k / m); z = 1.0 z = (double)k / (double)m; z = 1.25 Functions The type of the return value Function name Input arguments void myfunction(double arg1, int arg2) { /* Function body */ } Function body enclosed with braces void is used when the function does not return a value Modeling and Simulation: C intro 19 Modeling and Simulation: C intro 20

Functions (cont.) A function must be declared before it can be referenced A function can only call other functions declared above in the code Work-a-round Include a function prototype in the beginning, or, even better, in a header file Syntax ftype fname(arg_type_list); void myfunction(double,int); Note the semi-colon in the end and that only the types of the input arguments need to be given Modeling and Simulation: C intro 21 Functions (cont.) The return statement is used to return a value from a function Only one value can be returned Syntax return expression; Examples return 0; return(a+b); return; Can be written with or without parentheses Return from a function without return value Modeling and Simulation: C intro 22 The main function The function main is the first function that is executed in C programs Working as an interface between the calling environment and the program Should only include necessary code for initializing the program Call other functions to do the work! Return 0 (zero) if executed without error, otherwise a non-zero integer value The main function (cont.) A program without input arguments int main(void) {... } A program with input arguments int main (int argc, char *argv[]) {... } Number of arguments Argument vector Modeling and Simulation: C intro 23 Modeling and Simulation: C intro 24

Text output Print to screen (require stdio.h) Syntax int printf(const char format,...); int a = 3; printf( The value of a is %d\n,a); List of variables to be printed %d is called a placeholder (here for an integer). Always begins with %. Other common placeholders are: %c (character), %s (string), %f (floating-point number), and %e (floating-point number in scientific notation) \n writes a newline escape sequence Operators True/False A nonzero value (usually 1) is true Zero (0) is false Relational and equality operators <, >, <=, >=, ==,!= Do not mix-up == (equality) with = (assignment) Logical operators && (and), (or),! (not) Modeling and Simulation: C intro 25 Modeling and Simulation: C intro 26 Compound arithmetic operators Assignments +=, =, =, /=, and %= Example a = a + b; a += b; Incremental a++ : increase a by one (eq. to a = a + 1) b-- : decrease b by one (eq. to b = b 1) The for statement Syntax for ( initialization expression; loop repetition condition; update expression) { statements } Example for (i = 0; i < n; i++) { /* Do something */ } Modeling and Simulation: C intro 27 Modeling and Simulation: C intro 28

Pointers A pointer holds a memory adress to where some data is stored Denoted by a star ( ) at declaration int *nr_pigs; Pointer to an int No memory is allocated for the storage of the data. Must be done explicitly! Do not forget to deallocate memory! Pointers (cont.) int *a, b Access the data to which the pointer points to Star ( ) before pointer *a = 6; b = *a; Get the adress where a variable s data is stored And (&) before variable a = &b; Modeling and Simulation: C intro 29 Modeling and Simulation: C intro 30 Pointers (cont.) NULL as the value of a pointer indicates points to nothing Often used as return-value when something has gone wrong Good practice to initialize a new pointer to NULL int *nr_pigs = NULL; A void pointer is a pointer with no assigned data type void *unknown_type; Allocating/deallocating memory All functions for (de-)allocating memory require stdlib.h Allocate size bytes and return a pointer to the allocated memory void malloc(size_t size); Allocate memory for an array of nmemb elements of size bytes each and return a pointer to the allocated memory. The memory is initialized to zero void calloc(size_t nmemb, size_t size); Modeling and Simulation: C intro 31 Modeling and Simulation: C intro 32

Allocating/deallocating memory Free the memory space pointed to by ptr void free(void ptr); Reallocating void realloc(void ptr, size_t size); Get size of a data type (value of size above) size_t sizeof(type) Each malloc/calloc must be followed by a free! size_t corresponds to the integral data type returned by the language operator sizeof. It is machine dependent and usually an unsigned int or Modeling and Simulation: C intro 33 Pointers Example #include<stdio.h> #include<stdlib.h> int main(void) { int *a, *b; int x = 5; a = malloc(sizeof(int)); if ( a == NULL ) { fprintf(stderr, Failed to allocate memory! ); return (0); } *a = 2; b = &x; x = *a; printf("a = %d, b = %d, x = %d\n",*a,*b,x); free(a); return (0); Check that memory allocation didn t fail. If so, print an error message and exit. What is printed? Do not forget to free } allocated memory! unsigned long int. Modeling and Simulation: C intro 34 Arrays Arrays (cont.) An array is a data structure with indexed elements of the same data type Lists, vectors, etc. (one-dimensional) Matrices, Grids, etc. (two-dimensional) At declaration, the size is given in pair of brackets Tip: For arrays with static size, define the size with #define #define MAX_LENGTH 10... int list[max_length]; Modeling and Simulation: C intro 35 Declaration One-dim. array list with 5 integers int list[5]; Two-dim. array A of size 25 10 int A[25][10]; Initialization at declaration int list[] = {4,1,5,9,1000}; int A[3][2] = {{2,1},{3,4},{10,5}}; int B[][10] = {{3,4,1},{1,10,3,9}}; Modeling and Simulation: C intro 36

Arrays (cont.) The array subscript is enclosed in brackets The array subscript must be in the range 0 (zero) to one less than the length of the array It is up to the programmer to check validity of subscript Referencing elements outside the range may cause unwanted side effects or the program to crash Arrays (cont.) Assignment int list[2], elem0, elem1, elem2; list[0] = 1; elem0 = list[0]; elem1 = list[1]; elem2 = list[2]; Ok Problem Invalid! Modeling and Simulation: C intro 37 Modeling and Simulation: C intro 38 Arrays (cont.) The array name is a pointer to the first element in the array Possible to reach other memory cells by using the pointer list; list+1 is the next address. Note! Pointer arithmetic (list+1) is the value of the next integer Similar expressions list &list[0] list[0] *list list[3] *(list+3) Arrays (cont.) Multi-dimensional arrays (e.g., matrices) s double A[5][6], B[3][8][10][10]; Similar expressions A &A[0][0] A[0][0] **A A[1][3] *(A[1]+3) Modeling and Simulation: C intro 39 Modeling and Simulation: C intro 40