Upload
gpsoftsk
View
722
Download
1
Embed Size (px)
Citation preview
C101 – Intro to Programming with C
Peter Gaal
Introduction
• Your Name
• Your day job
• Your last holiday destination?
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
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
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)
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)
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
Usage of C
• Embedded devices
• System programming
• Operating systems
• Drivers
• Libraries
• Low power, high performance apps
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
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
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
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)
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
Now seriously, this is a real C code in the libraries (ffmpeg.c, ~line 327):
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
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
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)
C/C++ File structure
Header files*.h (usually C)
*.hpp (C++)
Source files*.c (usually C)
*.cpp (C++)
library files*.lib, *.a
C/C++ 101 – Intro to Programming with C/C++
Writing your first program in C
Hello, World!
Source: http://profitswithjody.com/wp-content/uploads/2012/11/hello_world_Wallpaper_5ze28.jpg
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");
}
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
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
Congratulations!
/* 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
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
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
Basic Definitions
• Variable - a name that refers to a value.
• Assignment statement - associates a value with a variable.
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
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
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
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
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;
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
Concatenating strings
/* make sure there is enough memory
for the result */
char result[100];
strcpy(result, “Hello “);
strcat(result, “World”);
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
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.
Hands-on Exercise
Command Line Arguments
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");
}
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
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");
}
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]);
}
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.
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
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 + - * /
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!
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
Hands-on Exercise
Integer Operations
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
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