3. 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
4. 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
5. 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)
6. 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)
7. History of C++
• 1989, C++ 2.0: multiple inheritance, abstract
classes, static member functions, const
member 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
8. Usage of C
• Embedded devices
• System programming
• Operating systems
• Drivers
• Libraries
• Low power, high performance apps
9. 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
10. 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
11. 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
12. 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)
13. 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 PC
nixon republican democrat Gates Mac PC
bush republican democrat
kennedy republican democrat
lincoln republican democrat Source: http://www.ioccc.org/2013/cable1/cable1.c
The International Obfuscated C Code Contest, year 2013
14. Now seriously, this is a real C code in the libraries (ffmpeg.c, ~line 327):
15. 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
16. How C/C++ works
Source code files
(mostly platform
independent)
.c, .h, .cpp, .hpp
Compiler
obj 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
17. How C/C++ works on different platforms
Source code files
(mostly platform
independent)
.c, .h, .cpp, .hpp
Compiler + Linker
Win32 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 + Linker
Linux x86
Linux x86 Binary (executable)
Dynamically linked libraries
x86 (.so)Linux x86 libraries (.a)
Compiler + Linker
Linux ARM
Linux ARM Binary (executable)
Dynamically linked libraries
ARM (.so)Linux ARM libraries (.a)
21. 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, worldn");
}
22. 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
23. 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
25. /* Prints “Hello, World” */
#include <stdio.h>
int main()
{
printf("Hello, worldn");
}
C program structure
Comments Included header files (other libraries)
Function
Arguments (we will
have them later)
HelloWorld.c
26. Language Features
Basic 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
Memory
Management
malloc()
free()
realloc()
sizeof()
Qualifiers
const
volatire
Pre-processor
Macros
#include
#define
#ifdef
#endif
Calling
Convention
cdecl
stdcall
fastcall
Memory
Types
code
stack
heap
27. Built-in Data Types
type set of values literal values operators
char Characters
Numbers (-128..127)
‘A’, ‘@’, ‘0’
65, 32, 0
Compare
int integers 17
12345
add, subtract,
multiply, divide
double Floating-point numbers 3.1415
6.022e23
add, subtract,
multiply, divide
bool Truth values true
false
and, or, not
28. Basic Definitions
• Variable - a name that refers to a value.
• Assignment statement - associates a value
with a variable.
29. 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
30. 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
31. 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
33. 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;
34. 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
35. Concatenating strings
/* make sure there is enough memory
for the result */
char result[100];
strcpy(result, “Hello “);
strcat(result, “World”);
36. Concatenating strings with other types
• Use string formatting functions
Expression (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
37. 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 path
argv[1] is the first argument
argv[2] is the second argument, etc.
39. 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");
}
40. 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
41. 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");
}
42. 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]);
}
43. 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.
44. Integer Data Type
Expression 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
45. 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 + - * /
46. 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!
47. 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
49. 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
50. 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 = %dn", a, b, sum);
printf("%d * %d = %dn", a, b, prod);
printf("%d / %d = %dn", a, b, quot);
printf("%d %% %d = %dn", a, b, rem);
}
> IntOps 1234 99
1234 + 99 = 1333
1234 * 99 = 122166
1234 / 99 = 12
1234 % 99 = 46