Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Similar documents
From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

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

PRINCIPLES OF OPERATING SYSTEMS

Dynamic memory allocation (malloc)

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C

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

Dynamic memory allocation

Array Initialization

CS24 Week 2 Lecture 1

Quick review pointer basics (KR ch )

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

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

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

CS201 - Lecture 1 The C Programming Language

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018


Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Class Information ANNOUCEMENTS

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Dynamic Memory Allocation and Command-line Arguments

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

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

Arrays and Memory Management

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

ECE 250 / CS 250 Computer Architecture. C Programming

Fundamental of Programming (C)

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Kurt Schmidt. October 30, 2018

ch = argv[i][++j]; /* why does ++j but j++ does not? */

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

LAB 1: C PRIMER CS444/544 WENJIN HU JAN 16TH, 2009

An overview of Java, Data types and variables

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

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

C - Basics, Bitwise Operator. Zhaoguo Wang

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

CS201- Introduction to Programming Current Quizzes

CSE 374 Programming Concepts & Tools

EL2310 Scientific Programming

Memory Allocation in C

Programming in C. What is C?... What is C?

Computer Programming. The greatest gift you can give another is the purity of your attention. Richard Moss

High Performance Programming Programming in C part 1

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

Advanced Pointer Topics

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Lecture 8 Dynamic Memory Allocation

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

CSE 303: Concepts and Tools for Software Development

CS 0449 Sample Midterm

Today s class. Review of more C Operating system overview. Informationsteknologi

CSE 333 Lecture 7 - final C details

The Compilation Process

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

In Java we have the keyword null, which is the value of an uninitialized reference type

CS61C : Machine Structures

MODULE 5: Pointers, Preprocessor Directives and Data Structures

CS 61c: Great Ideas in Computer Architecture

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

Final CSE 131B Spring 2004

Lecture 3: C Programm

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

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

211: Computer Architecture Summer 2016

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

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

EL2310 Scientific Programming

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

PROGRAMMAZIONE I A.A. 2017/2018

COMP 2355 Introduction to Systems Programming

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

ECE 250 / CPS 250 Computer Architecture. C Programming

C for C++ Programmers

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

CSE 303 Lecture 8. Intro to C programming

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

CSC C69: OPERATING SYSTEMS

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

CS61, Fall 2012 Section 2 Notes

Topic 6: A Quick Intro To C

Programming in C. UVic SEng 265. Daniel M. German Department of Computer Science University of Victoria. October 23, 2002 Version: 1.

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Work relative to other classes

just a ((somewhat) safer) dialect.

COMP s1 Lecture 1

Section 2: Processes

Transcription:

Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison of C, Java and Python Hello world Preprocessor Command line arguments Arrays and structures Pointers and dynamic memory 1-1- Datorarkitektur 2009 1-2- Datorarkitektur 2009 Operators in Python and C Python C Comment +, -, *, /, %, >>, << The same ** Does not exist Have to use function Does not exist ++, -- x++, ++x =, +=, *=,... The same <, <=, >, >=, ==,!= The same <> Does not exist Use!= &,, ^ The same and, or, not &&,,! in Does not exist Have to use function Does not exist? : Conditional If-statements and blocks in Python and C Python C Comment if test1: if (test1)... statement1 statement1;... is a block, it statement2 statement2; can be used to put several elif test2: else if (test2) statements where one statement3 statement3; statement is expected. else else In Python this is done by statement4 statement4; indentation. In C identation statement5 statement5; is purely for readability. Statements in C are ended by ;. 1-3- Datorarkitektur 2009 1-4- Datorarkitektur 2009

Other control flow in Python and C Python C Comment while test: while (test) statement statement; or a block of statements. do statement; while (test); for i in range(100): int i; statement for (i=1; i <= 100; i++) statement; or a block. or a block. statement is at least executed once. switch () case 1:... Multiple choise. break; break; Jump out of loop. continue; Go directly to next round. 1-5- Datorarkitektur 2009 Variable declaration in C A file of C-code consists of global variables and functions. In Python a variable is created when you first use it. In C a variable must be declared before it can be used. A variable is either global or local. A global variable is declared outside of functions. A local variable is a function parameter or declared at the beginning of a block inside a function. The content of a block consists of some variable declarations and then some statements. Functions are always global, they can't be declared inside a function. int x; Global variable x = 5; foo (int y, float z) int i; int x;... Local variables This local variable shadows the global variable. This means that inside the function foo, the local variable x is used not the global variable x. 1-6- Datorarkitektur 2009 Simple Data Types Gotchas (1) datatype size values char 1-128 to 127 short 2-32,768 to 32,767 int 4-2,147,483,648 to 2,147,483,647 long 4-2,147,483,648 to 2,147,483,647 (long long 8-9,223,372,036,854,775,808 to 9,223,372,036,854,775,087) float 4 3.4E+/-38 (7 digits) double 8 1.7E+/-308 (15 digits long) int i; for(i = 0; i < 10; i++) NOT (as in Java) for(int i = 0; i < 10; i++) 1-7- Datorarkitektur 2009 1-8- Datorarkitektur 2009

Gotchas (2) Uninitialized variables catch with Wall compiler option #include <stdio.h> int i; factorial(i); here. This variable is declared but has not a given value when it is used Gotchas (3) Error handling No exceptions. No try but there is longjump which has similarities. Must look at return values 1-9- Datorarkitektur 2009 1-10- Datorarkitektur 2009 Hello World #include <stdio.h> The file helloworld.c /* print a greeting */ printf("hello World!\n"); $> gcc -o helloworld helloworld.c # Compile the file Edit, Compile, Run C is a compiled language. Program in 3 steps: Edit file. Creates helloworld.c Compile. helloworld.c -> helloworld Run program helloworld $>./helloworld # Run the program Hello World! $> 1-11- Datorarkitektur 2009 An interpreted language like Python is used in 2 steps: Edit and Run 1-12- Datorarkitektur 2009

Breaking down the code #include <stdio.h> Include the contents of the file stdio.h Case sensitive lower case only No semicolon at the end of line int main( ) The OS calls this function when the program starts running. printf(format_string, arg1, ) Prints out a string, specified by the format string and the arguments. format_string Composed of ordinary characters (not %) Copied unchanged into the output Conversion specifications (start with %) Fetches one or more arguments For example char %c char* %s int %d float %f For more details: man -s 3 printf 1-13- Datorarkitektur 2009 1-14- Datorarkitektur 2009 Compilation steps C Preprocessor Compilation is done in several steps: Preprocessor Command gcc -E prog.c > proge.c Converts prog.c -> proge.c #define FIFTEEN_TWO_THIRTEEN \ "The Class That Gives CMU Its Zip\n" Actual compilation Assembling Linking gcc -x cpp-output -S proge.c gcc -c prog.s gcc -o prog prog.o proge.c -> prog.s prog.s -> prog.o prog.o -> prog printf(fifteen_two_thirteen); 1-15- Datorarkitektur 2009 1-16- Datorarkitektur 2009

After the preprocessor (gcc E) int main(int argc, char* argv) printf("the Class That Gives CMU Its Zip\n"); #define CS213 Conditional Compilation int main(int argc, char* argv) #ifdef CS213 printf("the Class That Gives CMU Its Zip\n"); #else printf("some other class\n"); #endif /* CS213 */ 1-17- Datorarkitektur 2009 1-18- Datorarkitektur 2009 After the preprocessor (gcc E) int main(int argc, char* argv) printf("the Class That Gives CMU Its Zip\n"); Command Line Arguments (1) argc Number of arguments (including program name) argv Array of char* (that is, an array of c strings) argv[0]: = program name argv[1]: = first argument argv[argc-1]: last argument 1-19- Datorarkitektur 2009 1-20- Datorarkitektur 2009

Command Line Arguments (2) Command Line Arguments (3) #include <stdio.h> int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n", i, argv[i]); 1-21- Datorarkitektur 2009 $./cmdline The Class That Gives CMU Its Zip 8 arguments $ 0:./cmdline 1: The 2: Class 3: That 4: Gives 5: CMU 6: Its 7: Zip 1-22- Datorarkitektur 2009 Arrays char foo[80]; An array of 80 characters sizeof(foo) = 80 x sizeof(char) = 80 x 1 = 80 bytes int bar[40]; An array of 40 integers sizeof(bar) = 40 x sizeof(int) = 40 x 4 = 160 bytes 1-23- Datorarkitektur 2009 Aggregate data: structures #include <stdio.h> struct person char* name; int age; ; /* <== DO NOT FORGET the semicolon */ struct person bovik; bovik.name = "Harry Bovik"; bovik.age = 25; printf("%s is %d years old\n", bovik.name, bovik.age); 1-24- Datorarkitektur 2009

Pointers Pointer variables are variables that hold an address in memory. That address can be the address of another variable. Memory layout and addresses int x = 5, y = 10; float f = 12.5, g = 9.8; char c = c, d = d ; 5 10 12.5 9. 8 c d 4300 4304 4308 4312 4317 4316 1-25- Datorarkitektur 2009 1-26- Datorarkitektur 2009 Using Pointers (1) float f; /* data variable */ float *f_addr; /* pointer variable */ f f_addr any float??? 4300 4304 any address f_addr = &f; /* & = address operator */ f f_addr? 4300 4300 4304 1-27- Datorarkitektur 2009 Pointers made easy (2) *f_addr = 3.2; /* * = indirection operator */ f f_addr 4300 4304 float g = *f_addr;/* indirection: g is now 3.2 */ f = 1.3; /* but g is still 3.2 */ f 3.2 4300 f_addr 1.3 4300 3.2 4300 4304 4308 1-28- Datorarkitektur 2009 g

Function Parameters Example 1: swap_1 Function arguments are passed by value. What is pass by value? The called function is given a copy of the arguments. What does this imply? The called function can t alter a variable in the caller function, only its private copy. Three examples int x = 3; int y = 4; void swap_1(int a, int b) int temp; temp = a; a = b; b = temp; Q: After swap_1(x,y); x =? y=? A1: x=4; y=3; A2: x=3; y=4; 1-29- Datorarkitektur 2009 1-30- Datorarkitektur 2009 Example 2: swap_2 Example 3: scanf int x = 3; int y = 4; void swap_2(int *a, int *b) int temp; temp = *a; *a = *b; *b = temp; Q: After swap_2(&x,&y); x =? y=? A1: x=4; y=3; A2: x=3; y=4; #include <stdio.h> int main() int x; scanf( %d\n, &x); printf( %d\n, x); Q: Why using pointers in scanf? A: We need to assign the value to x. 1-31- Datorarkitektur 2009 1-32- Datorarkitektur 2009

Dynamic Memory Pyton and Java manages memory for you, C does not C requires the programmer to explicitly allocate and deallocate memory Unknown amounts of memory can be allocated dynamically during run-time with malloc() and deallocated using free() Not like Java or Python No new No garbage collection You ask for n bytes Not a high-level request such as I d like an instance of class String 1-33- Datorarkitektur 2009 1-34- Datorarkitektur 2009 malloc Allocates memory in the heap Lives between function invocations Example Allocate an integer int *iptr = (int *) malloc(sizeof(int)); Allocate a structure You have to do a cast as malloc always returns a char * pointer struct name *nameptr = (struct name *) malloc(sizeof(struct name)); free Deallocates memory in heap. Pass in a pointer that was returned by malloc. Example int *iptr =(int *) malloc(sizeof int)); free(iptr); Caveat: don't use freed memory and don t free the same memory block twice! Must remember to free allocated memory 1-35- Datorarkitektur 2009 1-36- Datorarkitektur 2009

Linked list In C a linked list of strings is constructed with structs in dynamic memory thus: #include <stdio.h> struct node char *data; struct node *next; *list; data data list = NULL; struct node *p; for (i = 1; i < argc; i++) p = (struct node*) malloc(sizeof(struct node)); p -> next = list; p -> data = argv[i]; list = p; while (list!= NULL) printf(" %s", list -> data); p = list; list = list -> next; free(p); putchar('\n'); 1-37- Datorarkitektur 2009