c101 – intro to programming with c

50
C101 – Intro to Programming with C Peter Gaal

Upload: gpsoftsk

Post on 28-Jan-2018

722 views

Category:

Education


1 download

TRANSCRIPT

Page 1: C101 – Intro to Programming with C

C101 – Intro to Programming with C

Peter Gaal

Page 2: C101 – Intro to Programming with C

Introduction

• Your Name

• Your day job

• Your last holiday destination?

Page 3: C101 – Intro to Programming with C

C language overview

• procedural, general purpose, cross platform

• available almost on every platform

• Widely used

• Statically typed with weak typing

• Manual memory management, low memory footprint

• C is not object oriented but C++ and Objective-C has OOP support

Page 4: C101 – Intro to Programming with C

C++ language overview

• OOP support (classes)

• available on all major platforms (except embedded devices with small memory)

• Widely used

• Statically typed, strong typing

• Manual memory management (mostly), low memory footprint

Page 5: C101 – Intro to Programming with C

History of C

• general-purpose, procedural programming language, weak typing

• First appeared around year 1972, initially developed in AT&T Bell Labs and was used to (re-)implement the Unix operating system

• In 1989 became ANSI standard (C89)

• Updated in 1999 - C99 and in 2011 - C11 (not all compilers support it)

Page 6: C101 – Intro to Programming with C

History of C++

• Created by Bjarne Stroustrup in 1979, initially called "C with Classes“

• features: class, derived class, strong typing, inlining, and default argument

• 1983: it was renamed from C with Classes to C++

• new features: virtual functions, function name and operator overloading, references, constants, type-safe free-store memory allocation (new/delete)

Page 7: C101 – Intro to Programming with C

History of C++

• 1989, C++ 2.0: multiple inheritance, abstract classes, static member functions, constmember functions, and protected members

• 1990: templates, exceptions, namespaces, new casts, boolean type

• 1998: became an ISO standard, known as C++98

• recently new major updates: C++11, C++14, C++17

Page 8: C101 – Intro to Programming with C

Usage of C

• Embedded devices

• System programming

• Operating systems

• Drivers

• Libraries

• Low power, high performance apps

Page 9: C101 – Intro to Programming with C

Usage of C++

• All high performance/low power apps, similar to C but where we need classes

• Games

• Low latency

• Computer vision

• 3D graphics, video, audio

• Compression/decompression

Page 10: C101 – Intro to Programming with C

Software written in C/C++

• Linux kernel (in C), Windows 95-10, Office, SQL, Exchange, VC++, VB, C# compiler

• JRE – Java runtime environment

• MySQL, Perl, PHP, Python, MongoDB

• Adobe Photoshop, VLC player

• Firefox, Internet explorer

Page 11: C101 – Intro to Programming with C

Advantages

• Speed, high performance (low power)

• Compact (low) memory usage

• Low level, “close to the metal”

• Deterministic application response (no garbage collection stops the app)

• Creates native code, no need to install Java or .NET runtime, good protection against reverse compilation

Page 12: C101 – Intro to Programming with C

Disadvantages

• Hard language, manual memory management, complicated bugs hard to debug like segmentation fault (access violation), memory leaks, dangling pointers, corruption of data, buffer overruns, therefore lower productivity, sometimes hard to read

• C/C++ compiler is slow due to complicated syntax (header files, macros)

Page 13: C101 – Intro to Programming with C

Why is C (C++) hard?• Because you can find or write code like this:

• or this:

• or this:

Hint: if you don’t know what the last code does try to run with these parameters:obama republican democrat or: Jobs Mac PCnixon republican democrat Gates Mac PCbush republican democratkennedy republican democratlincoln republican democrat Source: http://www.ioccc.org/2013/cable1/cable1.c

The International Obfuscated C Code Contest, year 2013

Page 14: C101 – Intro to Programming with C

Now seriously, this is a real C code in the libraries (ffmpeg.c, ~line 327):

Page 15: C101 – Intro to Programming with C

this is also a real C code (libx264.c, ~line 770):

• but you can write also a nice, readable code in C/C++• and you can write also bad, unreadable code in any other language

Page 16: C101 – Intro to Programming with C

How C/C++ works

Source code files(mostly platform

independent).c, .h, .cpp, .hpp

Compilerobj files

(platform dependent)

Library files (.a)(platform dependent)

Linker

Native executable code (binary file)Platform (CPU) dependent

(different output on every platform)main() function – program entry

Page 17: C101 – Intro to Programming with C

How C/C++ works on different platforms

Source code files(mostly platform

independent).c, .h, .cpp, .hpp

Compiler + LinkerWin32 x86

Win32 x86 Binary (.EXE)

Dynamically linked libraries (DLL) – x86Win32 x86 libraries

(.a, .lib)

Compiler + Linker Win 64bit

Windows 64bit Binary (.EXE)

Dynamically linked libraries (DLL) – 64bitWin 64bit libraries

(.a, .lib)

Compiler + LinkerLinux x86

Linux x86 Binary (executable)

Dynamically linked libraries x86 (.so)Linux x86 libraries (.a)

Compiler + LinkerLinux ARM

Linux ARM Binary (executable)

Dynamically linked libraries ARM (.so)Linux ARM libraries (.a)

Page 18: C101 – Intro to Programming with C

C/C++ File structure

Header files*.h (usually C)

*.hpp (C++)

Source files*.c (usually C)

*.cpp (C++)

library files*.lib, *.a

Page 19: C101 – Intro to Programming with C

C/C++ 101 – Intro to Programming with C/C++

Writing your first program in C

Page 20: C101 – Intro to Programming with C

Hello, World!

Source: http://profitswithjody.com/wp-content/uploads/2012/11/hello_world_Wallpaper_5ze28.jpg

Page 21: C101 – Intro to Programming with C

Writing your first program in C

• Create a new “Win32 Console application, Visual C++” in Visual C++ Express named MyFirstCProgram, select empty project on the application settings screen

• Create a new CPP file in “Source Files” in Solution Explorer HelloWorld.c as illustrated below:

/* Prints “Hello, World” */

#include <stdio.h>

int main()

{

printf("Hello, world\n");

}

Page 22: C101 – Intro to Programming with C

Compiling Your First C Program

• In Visual C++: Press “F7” or “Debug->Build Solution” from main menu

• It’s recommended to save your source files but it’s not required in Visual C++, other IDEs might require it

Page 23: C101 – Intro to Programming with C

Running Your First C Program

• Press Ctrl-F5 to Run your program in Visual C++

• Alternatively you can use F5 or “Debug->Start debugging” from main menu

Page 24: C101 – Intro to Programming with C

Congratulations!

Page 25: C101 – Intro to Programming with C

/* Prints “Hello, World” */

#include <stdio.h>

int main()

{

printf("Hello, world\n");

}

C program structureComments Included header files (other libraries)

Function

Arguments (we will have them later)

HelloWorld.c

Page 26: C101 – Intro to Programming with C

Language FeaturesBasic Built-In Types

int

char

float

double

bool

Type Modifiers

short (short int)

long (long int)

signed (by default)

unsigned (unsigned int)

Flow Control

if else

for while

Punctuation

{ {

( )

, ;

Assignment

=

Pointers

*

& (reference)

#include <stdio.h>

printf()

scanf()

Operators

+ - * /

% ++

-- >

< <= >= ==

!= >> <<

Derived Types

struct

enum

array

union

MemoryManagement

malloc()

free()

realloc()

sizeof()

Qualifiers

const

volatire

Pre-processor Macros

#include

#define

#ifdef

#endif

Calling Convention

cdecl

stdcall

fastcall

Memory Types

code

stack

heap

Page 27: C101 – Intro to Programming with C

Built-in Data Typestype set of values literal values operators

char CharactersNumbers (-128..127)

‘A’, ‘@’, ‘\0’65, 32, 0

Compare

int integers 1712345

add, subtract,multiply, divide

double Floating-point numbers 3.14156.022e23

add, subtract,multiply, divide

bool Truth values truefalse

and, or, not

Page 28: C101 – Intro to Programming with C

Basic Definitions

• Variable - a name that refers to a value.

• Assignment statement - associates a value with a variable.

Page 29: C101 – Intro to Programming with C

Strings

• In C there is no string type! (as it is in Java)

• But you can use strings as array of chars

• In C strings are NULL terminated (array of chars)

• String is a pointer to first letter (char in the array)Examples of strings (all strings are static)

defined length char str[20]=“Hello World”;

defined length without initial value char str[20];

automatic length (by compiler) char str[]=“Hello World”;

Automatic, pointer syntax char *str=“Hello World”;

same definition

Page 30: C101 – Intro to Programming with C

What is a pointer?A pointer is a variable which contains the address in memory of another variable.

Here is your Hello world string in the memory

Memory address, where your string is located

Here is the content of the pointer in the memory

(bytes are in reverse order because of the LITTLE endian architecture)

Memory address, where your pointer is located

points to a single byte in memory

Page 31: C101 – Intro to Programming with C

What is a NULL terminated string?

char str[] = “Hello”;

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ (null)

str[0] str[1] str[2] str[3] str[4] str[5]

• string is finished with a special char (null, ‘\0’)

• warning: ‘0’ is not ‘\0’

• “Hello” string with length 5 characters needs at least 6 characters (bytes) to store the string

Page 32: C101 – Intro to Programming with C

Strings

char str[6]=”Hello”;

char str[6];

str[0]=‘H’;

Str[1]=‘e’;

Str[2]=‘l’;

Str[3]=‘l’;

Str[4]=‘o’;

Str[5]=‘\0’;

This is the same functionality

Page 33: C101 – Intro to Programming with C

Strings

• You can’t concatenate string in a C with an operator (+ in Java or C#)

char *result;

char *string1 = “Hello “;

char *string2 = “World”;

result = string1 + string2;

Page 34: C101 – Intro to Programming with C

Strings

• You can concatenate strings using:

– strcat (and similar functions)

– printf (print formatted data to console)

– sprintf (write formatted data to string)

• You need to allocate enough memory for the destination string

• strcpy – makes a copy of string

Page 35: C101 – Intro to Programming with C

Concatenating strings

/* make sure there is enough memory

for the result */

char result[100];

strcpy(result, “Hello “);

strcat(result, “World”);

Page 36: C101 – Intro to Programming with C

Concatenating strings with other types

• Use string formatting functionsExpression (def.: char result[100]) Value

sprintf(result, “%s%s”, “Hi, “, “Bob”); “Hi, Bob”

sprintf(result, “Hi, %s”, “Bob”); “Hi, Bob”

sprintf(result, “%d %d %d”, 1, 2, 1); “1 2 1”

sprintf(result, “%d + %d”, 1234, 99); “1234 + 99”

sprintf(result, “%d%d”, 123, 99); “12399”

• If you need just to print on the console you can use printf instead of sprintf and you don’t need to allocate the string

Page 37: C101 – Intro to Programming with C

Command line arguments

#include <stdio.h>

int main(int argc, char *argv[]) {

}

argument count

array of string arguments

argv[0] is the program name with full pathargv[1] is the first argumentargv[2] is the second argument, etc.

Page 38: C101 – Intro to Programming with C

Hands-on Exercise

Command Line Arguments

Page 39: C101 – Intro to Programming with C

Command Line Arguments

• Create a program that takes a name as command-line argument and prints “Hi <name>, How are you?”

#include <stdio.h>

int main(int argc, char *argv[])

{

printf("Hi, ");

printf(argv[1]);

printf(". How are you?\n");

}

Page 40: C101 – Intro to Programming with C

Command Line Arguments

• You need to pass an argument into your command line application, otherwise it will crash or will do nothing

• Press Alt-F7 (or menu Project->Properties), expand Configuration Properties, select Debugging and in the second line you will see “Command arguments”

• Type here your name, then press OK and run the program again

• In the next exercise if you will need more than one argument then just put spaces between each argument

Page 41: C101 – Intro to Programming with C

Command Line Arguments

• You shouldn’t pass an unverified string from your command line directly into printf function, so we will modify it:

#include <stdio.h>

int main(int argc, char *argv[])

{

printf("Hi, ");

printf("%s", argv[1]);

printf(". How are you?\n");

}

Page 42: C101 – Intro to Programming with C

Command Line Arguments

• You can do the previous program with just one printf function now:

#include <stdio.h>

int main(int argc, char *argv[])

{

printf("Hi, %s. How are you?\n",

argv[1]);

}

Page 43: C101 – Intro to Programming with C

Integer Data Type

Data Type Attributes

Values Integers between -2E31 to +2E31-1

Typical literals 1234, -99 , 99, 0, 1000000

Operation Add subtract multiply divide remainder

Operator + - * / %

• Useful for expressing algorithms.

Page 44: C101 – Intro to Programming with C

Integer Data TypeExpression Value Comment

5 + 3 8

5 – 3 2

5 * 3 15

5 / 3 1 no fractional part

5 % 3 2 remainder

1 / 0 run-time error

3 * 5 - 2 13 * has precedence

3 + 5 / 2 5 / has precedence

3 – 5 - 2 -4 left associative

(3-5) - 2 -4 better style

3 – (5-2) 0 unambiguous

Page 45: C101 – Intro to Programming with C

Double Data Type

• Useful in scientific applications and floating-point arithmetic

• float is a type with a “half precision”

• sizeof(float)=4, sizeof(double)=8 (in Bytes)

Data Type Attributes

Values Real numbers specified by the IEEE 754 standard

Typical literals 3.14159 6.022e23 -3.0 2.0 1.41421356237209

Operation Add subtract multiply divide

Operator + - * /

Page 46: C101 – Intro to Programming with C

Double Data Type

Expression Value

3.141 + 0.03 3.171

3.141 – 0.03 3.111

6.02e23 / 2 3.01e23

5.0 / 3.0 1.6666666666667

10.0 % 3.141 0.577

1.0 / 0.0 Infinity (INF)

sqrt(2.0)(#include <math.h>)

1.4142135623730951

not defined in C!

Page 47: C101 – Intro to Programming with C

C Math Library (#include <math.h>)

Methods

sin() cos()

log() exp()

sqrt() pow()

fmin() fmax()

abs()

http://java.sun.com/javase/6/docs/api/java/lang/Math.html

• PI constant: you can define by yourself:#define PI 3.14159265358979323846

Page 48: C101 – Intro to Programming with C

Hands-on Exercise

Integer Operations

Page 49: C101 – Intro to Programming with C

Exercise: Integer Operations

• Create new Win32 console application empty project in Visual C++ called IntOps

• Create a source file named IntOps.c that performs integer operations on a pair of integers from the command line and prints the results.

> IntOps 1234 99

1234 + 99 = 1333

1234 * 99 = 122166

1234 / 99 = 12

1234 % 99 = 46

Page 50: C101 – Intro to Programming with C

Solution: Integer Operations#include <stdio.h>

int main(int argc, char *argv[])

{

int a,b;

int sum, prod, quot, rem;

sscanf(argv[1],"%d", &a);

sscanf(argv[2],"%d", &b);

sum = a + b;

prod = a * b;

quot = a / b;

rem = a % b;

printf("%d + %d = %d\n", a, b, sum);

printf("%d * %d = %d\n", a, b, prod);

printf("%d / %d = %d\n", a, b, quot);

printf("%d %% %d = %d\n", a, b, rem);

}

> IntOps 1234 99

1234 + 99 = 1333

1234 * 99 = 122166

1234 / 99 = 12

1234 % 99 = 46