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

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

PRINCIPLES OF OPERATING SYSTEMS

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

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

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

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

Array Initialization

Kurt Schmidt. October 30, 2018

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

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

Work relative to other classes

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

COMP 2355 Introduction to Systems Programming

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

The C language. Introductory course #1

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

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

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

Intermediate Programming, Spring 2017*

Data Representation and Storage. Some definitions (in C)

High Performance Programming Programming in C part 1

C Programming Review CSC 4320/6320

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

Understanding Pointers

Arrays and Pointers in C. Alan L. Cox

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

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

Principles of C and Memory Management

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

Data Representation and Storage

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

Princeton University COS 333: Advanced Programming Techniques A Subset of C90

Programming in C UVic SEng 265

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

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

Chapter IV Introduction to C for Java programmers

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

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

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

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

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

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

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

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

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

ARRAYS(II Unit Part II)

Variables and literals

BSM540 Basics of C Language

A Short Course for REU Students Summer Instructor: Ben Ransford

C Syntax Out: 15 September, 1995

CSE 303 Lecture 8. Intro to C programming

CS 241 Data Organization Pointers and Arrays

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Review of the C Programming Language for Principles of Operating Systems

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

Luar Topics. C A Low level Programming Language Make A dependency based build system YUYV Representation of Color ZMP Zero Moment Point control

Contents. A Review of C language. Visual C Visual C++ 6.0

Dynamic memory allocation

CS61, Fall 2012 Section 2 Notes

Character Strings. String-copy Example

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

CS C Primer. Tyler Szepesi. January 16, 2013

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

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

CSE 333 Lecture 2 Memory

CSC231 C Tutorial Fall 2018 Introduction to C


CS 61c: Great Ideas in Computer Architecture

CSCI 350: Getting Started with C Written by: Stephen Tsung-Han Sher June 12, 2016

Lectures 5-6: Introduction to C

Answer all questions. Write your answers only in the space provided. Full marks = 50

Topic 6: A Quick Intro To C

EL2310 Scientific Programming

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

ECE264 Fall 2013 Exam 3, November 20, 2013

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

Lecture 02 C FUNDAMENTALS

These problems are provided to you as a guide for practice. The questions cover important concepts covered in class.

Language comparison. C has pointers. Java has references. C++ has pointers and references

CS 222: Pointers and Manual Memory Management

CS201 - Lecture 1 The C Programming Language

CS 0449 Sample Midterm

Pointers (continued), arrays and strings

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Common Misunderstandings from Exam 1 Material

Fundamental of Programming (C)

A Fast Review of C Essentials Part I

EM108 Software Development for Engineers

Review of the C Programming Language

Introduction to C. Systems Programming Concepts

Programming in C - Part 2

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

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

ECE 250 / CPS 250 Computer Architecture. C Programming

Input And Output of C++

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


Transcription:

Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo

Compilation #include <stdio.h> int main() { printf("hello World!\n"); return 0; } Main compilation flags: $ gcc o hello hello.c // -o: to specify executable name $ gcc Wall hello.c // -Wall Wall: gives much better warnings $ gcc g hello.c // -g: to enable debugging with gdb $ gcc O hello.c // -O: to turn on optimization DCC-FCUP # 1

char a = 'A'; char b = 65; char c = 0x41; Data Types: Examples int i = -2343234; unsigned int ui = 4294967295; unsigned int uj = ((long) 1 << 32) - 1; unsigned int uk = -1; float pi = 3.14; double long_pi = 0.31415e+1; DCC-FCUP # 2

Integer Data Types There is no explicit boolean data type: Values 0 or NULL mean FALSE Any other value means TRUE DCC-FCUP # 3

Floating-Point Data Types To get the exact size of a data type or variable, use the sizeof() operator that yields the storage size of the type or variable in bytes: int x; printf("storage size for type int: %d bytes\n", sizeof(int int)) )); printf("storage size for variable x: %d bytes\n", sizeof(x)) )); DCC-FCUP # 4

Void Data Type The void data type specifies that no value is available and it can be used in three kinds of situations: DCC-FCUP # 5

Arithmetic Operators DCC-FCUP # 6

Relational Operators DCC-FCUP # 7

Logical Operators DCC-FCUP # 8

Bitwise Operators DCC-FCUP # 9

Decision Making Statements If statement if (cond cond) {... // continue here if cond is true else {... // continue here if cond is false } Switch statement switch (val val) { case constx:... // continue here if val is constx break;... default:... // continue here if all other cases fail } DCC-FCUP # 10

Loop Control Statements For statement for (pre_cond pre_cond; cond; post_loop) {... // execute pre_cond once and loop while cond is true } // at the end of each loop, execute post_loop While statement while (cond cond) {... // loop while cond is true } Do/while statement do {... // execute once and loop while cond is true } while (cond cond); DCC-FCUP # 11

Pointers A pointer is a variable whose value is a memory address The general form of a pointer variable declaration is type *ptrname ptrname; where type is the pointer's base data type and ptrname is the name of the pointer variable: char *ch ch; // pointer to a character int *ip ip; // pointer to an integer float *fp fp; // pointer to a float int **ipp ipp; // pointer to a pointer to an integer There are two main pointer operations: & to obtain the memory address of something * to access the memory address stored in a pointer DCC-FCUP # 12

Pointers: Example I int main () { int v = 0; int *ip; // initially ip stores an undefined memory address ip = &v; // here ip stores the memory address of variable v // print address stored in pointer ip printf("value stored in ip variable: %x\n", ip); // change v s value using pointer ip *ip = 10; // print v s value using pointer ip printf("value stored in v variable: %d\n", *ip); return 0; } DCC-FCUP # 13

Pointers: Example II int *ip1, *ip2; step 1 step 3 int i = 5; int j = 3; // step 1 ip = &i; // step 2 *ip = 7; step 4 ip = &j; step2 // step 3 ip2 = ip; // step 4 ip = &i;... DCC-FCUP # 14

Arrays Arrays consist of contiguous memory locations used to store a fixed-size sequential collection of elements of the same type Each specific element in an array is accessed by an index The lowest index (0) corresponds to the first element and the highest address to the last element The general form of an array variable declaration is type arrayname[size]; where type is the data type of the elements, arrayname is the name of the array variable and size is the number of elements in the array: char cs[10 10]; // an array of 10 characters int is[5]; // an array of 5 integers DCC-FCUP # 15

Arrays Arrays can also be initialized when declaring them: int is[5] = {1000 1000, 2, 3, 7, 50}; int is[] = {1000 1000, 2, 3, 7, 50}; When declaring the size of the array, the number of values between braces { } cannot be larger than the number of elements declared for the array between square brackets [ ] When omitting the size of the array, an array just big enough to hold the initialization is created DCC-FCUP # 16

Arrays: Example int main () { int i,j; // declare an array of 10 integers int n[10 10]; // initialize elements of array for (i = 0; i < 10; i++) n[i] = i + 100; // output each array element's value for (j = 0; j < 10; j++) printf( element[%d] = %d\n", j, n[j]); return 0; } DCC-FCUP # 17

Strings A string is an array of characters terminated by the null character '\0' To hold the null character, the size of the array is one more than the number of characters in the string: char greeting[6] = {'H', 'e', 'l', ', 'l', 'o', '\0'}; Following the array initialization rule, we can also write: char greeting[] = "Hello"; "; char *greeting = "Hello"; DCC-FCUP # 18

Basic String Functions DCC-FCUP # 19

Basic String Functions: Example #include <stdio.h> #include <string.h> int main () { char str1[100] = "Hello"; char str2[100] = "World"; // concatenate str2 onto the end of str1 strcat(str1, str2); // copy str1 into str2 strcpy(str2, str1); // print length of str1 printf("str1 length: %d\n", strlen(str1)); } DCC-FCUP # 20

Functions While calling a function, there are two ways that arguments can be passed to a function: Call by value copies the actual value of an argument into the formal parameter of the function, meaning that changes made to the parameter inside the function have no effect on the argument Call by reference copies the address of an argument into the formal parameter and, inside the function, the address is used to access the actual argument used in the call, meaning that changes made to the parameter affect the argument By default, C uses call by value to pass arguments However, if we use pointer arguments in a function, we can implement a kind of call by reference for the variables pointed by the argument pointers and thus alter those variables inside the function DCC-FCUP # 21

Call by Value: Example void swap_call_by_value(int n1, int n2) { int temp = n1; n1 = n2; n2 = temp; } int main() { int n1 = 1; int n2 = 2; swap_call_by_value(n1, n2); printf("n1: %d n2: %d\n", n1, n2); // prints n1: 1 n2: 2 return 0; } DCC-FCUP # 22

Call by Reference: Example void swap_call_by_reference(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } int main() { int n1 = 1; int n2 = 2; swap_call_by_reference(&n1, &n2); printf("n1: %d n2: %d\n", n1, n2); // prints n1: 2 n2: 1 return 0; } DCC-FCUP # 23

Structures A structure is a user defined data type which allows to combine data items of different kinds The struct statement defines a new data type which can contain several different item members: struct [structure tag] { type1 item1; type2 item2;... typen itemn; } [one or more structure variables]; Similarly to arrays, structures can also be initialized when declaring them: struct list_elem le = {10 10, NULL}; DCC-FCUP # 24

struct list_elem { int data; struct list_elem *next; }; Structures: Example int main() { struct list_elem le = {10 10, NULL}; struct list_elem *lep = printf("data %d next %x\n", le.data data, le.next next); printf("data %d next %x\n", *lep.data data, *lep.next next); printf("data %d next %x\n", lep->data >data, lep->next >next); return 0; } DCC-FCUP # 25

Typedefs The keyword typedef allows to give a type a new identifier: typedef unsigned char BYTE; The new identifier can then be used as an abbreviation for the type: BYTE b1, b2; The typedef keyword can also be used to give a name to user defined data types. typedef struct { int data; struct list_elem *next next; } list_elem;... list_elem le = {10 10, NULL}; DCC-FCUP # 26

Dynamic Memory Allocation DCC-FCUP # 27

Dynamic Memory Allocation: Example #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // allocate memory dynamically char *name = malloc(20 * sizeof(char)); if (name = = NULL) { /* malloc error */ } else { strcpy(name, "Hello world!"); printf("%s "%s\n", name); } } DCC-FCUP # 28

Command Line Arguments int main(int int argc, char *argv[]) { if (argc = = 1) printf("he "Hello %s! s!\n", argv[1]); else printf("hello World!\n"); return 0; } Running example: $ gcc o hello hello.c $ hello Ricardo Hello Ricardo DCC-FCUP # 29

Preprocessor Directives The C Preprocessor is not part of the compiler, but a separate step in the compilation process that works like a text substitution tool DCC-FCUP # 30