Programming refresher and intro to C programming

Similar documents
A brief introduction to C programming for Java programmers

More on C programming

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

Topic 6: A Quick Intro To C

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

Lectures 5-6: Introduction to C

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

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

Lectures 5-6: Introduction to C

Communication. Serial port programming

ECEN 449 Microprocessor System Design. Review of C Programming

Work relative to other classes

Lecture 03 Bits, Bytes and Data Types

Embedded programming, AVR intro

PRINCIPLES OF OPERATING SYSTEMS

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

Computer Organization & Systems Exam I Example Questions

Introduction to Programming Using Java (98-388)

C - Basics, Bitwise Operator. Zhaoguo Wang

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Computers Programming Course 6. Iulian Năstac

EL2310 Scientific Programming

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

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

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Computer Systems Programming. Practice Midterm. Name:

CYSE 411/AIT681 Secure Software Engineering Topic #10. Secure Coding: Integer Security

CSE 12 Spring 2018 Week One, Lecture Two

2/9/18. Readings. CYSE 411/AIT681 Secure Software Engineering. Introductory Example. Secure Coding. Vulnerability. Introductory Example.

2/9/18. CYSE 411/AIT681 Secure Software Engineering. Readings. Secure Coding. This lecture: String management Pointer Subterfuge

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

A Fast Review of C Essentials Part I

Page 1. Where Have We Been? Chapter 2 Representing and Manipulating Information. Why Don t Computers Use Base 10?

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Number Systems for Computers. Outline of Introduction. Binary, Octal and Hexadecimal numbers. Issues for Binary Representation of Numbers

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

CSE 303 Lecture 8. Intro to C programming

Introduction to C An overview of the programming language C, syntax, data types and input/output

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

EL2310 Scientific Programming

Bits and Bytes. Why bits? Representing information as bits Binary/Hexadecimal Byte representations» numbers» characters and strings» Instructions

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

Pointers (continued), arrays and strings

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

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

Bit Manipulation in C

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

Pointers (continued), arrays and strings

EL2310 Scientific Programming

Kurt Schmidt. October 30, 2018

(T) x. Casts. A cast converts the value held in variable x to type T

Getting started with Java

COMP 2355 Introduction to Systems Programming

Advanced C Programming Topics

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

Variables and literals

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

CSE 374 Programming Concepts & Tools

Expressions & Flow Control

EC 413 Computer Organization

Bits, Bytes and Integers

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

CSE 12 Spring 2016 Week One, Lecture Two

Hardware: Logical View

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

High Performance Computing Lecture 1. Matthew Jacob Indian Institute of Science

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Zheng-Liang Lu Java Programming 45 / 79

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

Lecture 2: C Programm

CSC C69: OPERATING SYSTEMS

Arithmetic and Bitwise Operations on Binary Data

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Fundamental of Programming (C)

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

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

Course Outline Introduction to C-Programming

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

Lecture 5-6: Bits, Bytes, and Integers

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Lecture 3: C Programm

Arithmetic and Bitwise Operations on Binary Data

VARIABLES AND TYPES CITS1001

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

Representing and Manipulating Integers Part I

Reserved Words and Identifiers

CS 261 Fall Mike Lam, Professor. Structs and I/O

CC112 Structured Programming

Chapter 3: Operators, Expressions and Type Conversion

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

EL2310 Scientific Programming

C Language Summary. Chris J Michael 28 August CSC 4103 Operating Systems Fall 2008 Lecture 2 C Summary

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Programming. Syntax and Semantics

The C language. Introductory course #1

Fall 2017 CISC124 9/16/2017

CPSC 213. Introduction to Computer Systems. Numbers and Memory. Unit 1a

Transcription:

Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018

Outline 1 C programming intro 2 Structuring programs

Programming environment Compared to the introductory Java courses We recommend (and support) writing the host (PC) programs in C rather than Java the embedded (AVR) programs will be written in C console I/O is more straight-forward in C We provide no programming environment (for host), instead 1 Edit source code in any text editor 2 compile the source file(s) from the command line 3 run the generated executable You are free to use whatever you re familiar with C programming intro Programming refresher and intro to C programming 2/23

Compared to Java, C is not object-oriented: no classes has declarations in header (.h) files and code in.c files separate compilation C files may include.h files (similar to Java import clauses) is not type-safe (no runtime safety net) pointers instead of references be careful with type casts has no automatic memory management (GC) Be careful with (avoid) dynamic memory allocation C programming intro Programming refresher and intro to C programming 3/23

Hello world Java: class Hello { public static void main ( String args []){ System. out. print ln("hello, world!"); C: # include <stdio.h> int main (){ printf ("Hello, world!\n"); return 0; C programming intro Programming refresher and intro to C programming 4/23

Compiling and running from the command line Edit the source file hello.c From the (cygwin) command line 1 go to the directory where the source file is (e.g. src) > cd src 2 compile the source code > gcc - Wall -o hello hello.c 3 run the generated executable >./ hello or >./ hello. exe Set output file name to hello (defaults to a.out or a.exe) turn on compiler warnings C programming intro Programming refresher and intro to C programming 5/23

Paths in Cygwin and Windows The cygwin /home directory is in the windows directory C:\WP\cygwin\home The windows drives are mounted under /cygdrive. E.g., C: is accessible in cygwin at /cygdrive/c NB! Cygwin and Windows use different path separators C programming intro Programming refresher and intro to C programming 6/23

Programming recap, C examples C syntax similar to Java Control flow alternatives: if statments repetition: for and while statements Boolean expressions Array operations Terminal I/O (console, serial port) C programming intro Programming refresher and intro to C programming 7/23

if statements if( condition ) { then_statements... else { else_statements... else branch is optional condition is any integer (more on that) C programming intro Programming refresher and intro to C programming 8/23

while statements while ( condition ) { statements... do { statements... while ( condition ); Like in Java C programming intro Programming refresher and intro to C programming 9/23

for statements for ( init ; condition ; increment ) { statements... Example: int i; // NB! declaration outside of for statement for (i =0; i < 10; ++i) { printf ("%d ", i); will print 0 1 2 3 4 5 6 7 8 9 C programming intro Programming refresher and intro to C programming 10/23

printf??? the C standard I/O library has functions for formatted output (and input) to use: #include <stdio.h> output: printf(format, arguments...) where format is a string that may contain placeholders for the formatted values of the following arguments (in order of appearance). Example: int x = 10; float y = 12.8; printf ("x = %d, y = %f\n", x, y); More on this later C programming intro Programming refresher and intro to C programming 11/23

printf() format conversions character argument type; convert to d, i signed decimal notation x unsigned hexadecimal notation (w/o leading 0x) u unsigned decimal notation c single character (converted to char) f double in decimal notation [-]mmm.dddd s string (char *) the conversion characters may be preceeded with arguments for minimum width and/or precision. E.g., \%4.2f : min 4 chars wide, 2 decimal positions \%.8x : print (at least) 8 digits, padding with leading zeroes... and much more, consult a language reference C programming intro Programming refresher and intro to C programming 12/23

Boolean and bitwise operators Boolean operators (evaluate to true or false)! not && and or Bitwise operators (evaluate to a number) ~ not (bitwise complement) & and or ^ xor (exclusive or) C programming intro Programming refresher and intro to C programming 13/23

Boolean expressions Boolean expressions evaluate to true or false same syntax as in Java but there is no boolean type in C instead, any integer (and hence, any type) can be used zero is interpreted as false non-zero is interpreted as true Example: infinite loop while (1) { // corresponds to while ( true ) in Java printf ("."); C programming intro Programming refresher and intro to C programming 14/23

Primitive data types Similar to Java, but char: 8 bits (=byte) unsigned integer types available The common ones char unsigned char short unsigned short int unsigned int float double Type definitions for special purposes size_t, ssize_t, uint8, uint16, int8, int16 C programming intro Programming refresher and intro to C programming 15/23

unsigned integer types E.g, unsigned char, unsigned short, unsigned int Avoids sign extension signed char x = 0 xff ; unsigned char y = 0 xff ; int ix = x; // ix = -1, bit pattern 0 xffffffff int iy = y; // iy = 255, bit pattern 0 x000000ff Always use unsigned types when you care about a bit pattern, e.g., bit operations on HW registers etc. NB! On signed types, >> is implementation defined. Typically preserves the sign by shifting in ones (instead of zeroes) if the highest bit is 1 (i.e., a negative value). i For char, signed or unsigned must be specified (it is implementation defined if char is signed or unsigned), for the other types the default is signed (i.e., int is signed int). C programming intro Programming refresher and intro to C programming 16/23

arrays and strings arrays in C are similar to arrays of primitive types in Java, but must be allocated on the stack (or heap, but avoid that) have no length attribute or bounds checking have no type safety a string in C is really a pointer to a the first character of a char array. C programming intro Programming refresher and intro to C programming 17/23

arrays and strings, examples Integer array: int a [6]; int i; for (i=0; i <6; i++) { a[i] = 2 * (i +1); for (i=0; i <6; i++) { printf ("%d ", a[i ]); string (char array): char s[] = " hej "; int i; for (i=0; i <3; i++) { printf ("%c\n", s[i ]); s [1] = o ; for (i=0; i <3; i++) { printf ("%c\n", s[i ]); NB! char s[], not char *s to make it mutable C programming intro Programming refresher and intro to C programming 18/23

C strings are not like in Java null-terminated: the end of the string is marked by the character null (i.e., the integer value zero) no length information (i.e., no safety net) copy, concatenate etc using library functions get length by counting the number of chars from the start to the first null character. snprintf is a useful string builder like printf, but writes to a char[] make sure destination buffer is big enough C programming intro Programming refresher and intro to C programming 19/23

Array operations Syntax like in Java Example: int sum ( int numbers [], int len ) { int result =0; int i; for (i =0; i<len ; i ++) { result = result + numbers [i]; return result ; Unlike in Java, C does not do range checking, so the programmer must keep track of the length of arrays and avoid accessing past the end C programming intro Programming refresher and intro to C programming 20/23

Suggested array exercise read a string (char[] = char*) from the terminal Example of raw input using fgets: print it char buf [ BUFSIZE ]; // BUFSIZE -1 chars + terminating null char * res = fgets ( buf, BUFSIZE, stdin ); if (! res ) { // an error occured... print it backwards encode it in rövarspråket for each consonant C, replace C with CoC mekatronik momekokatotrorononikok C programming intro Programming refresher and intro to C programming 21/23

A word on coding style Factor your code into small functions One function should do only one thing Rule of thumb: a function should be at most 24 lines long, have at most three block levels, and have at most five local variables. If not, split into smaller functions Only use stack allocation Allocate buffers etc. in the main function I.e., (rule of thumb): The main function should only consist of variable declarations and (a few) function calls Structuring programs Programming refresher and intro to C programming 22/23

A typical main function Allocate storage Do initialization Call functions that do the main work Cleanup (deallocate/release resources) # include " myproj.h" # define BUFSIZE 100 int main () { unsigned char buffer [ BUFSIZE ]; FILE *f; f = init (); do_work (f, buffer, BUFSIZE ); cleanup (f); return 0; Structuring programs Programming refresher and intro to C programming 23/23

Next lecture Pointers and structs Number representation Bitwise operators Structuring programs Programming refresher and intro to C programming 24/23