SlideShare a Scribd company logo
C PROGRAMMING
DR ANTON GERDELAN
<GERDELA@SCSS.TCD.IE>
LEAP IN AND TRY THINGS. IF YOU SUCCEED,
YOU CAN HAVE ENORMOUS INFLUENCE. IF
YOU FAIL, YOU HAVE STILL LEARNED
SOMETHING, AND YOUR NEXT ATTEMPT IS
SURE TO BE BETTER FOR IT.
Brian Kernighan
C PROGRAMMING REFRESHER
C PROGRAMMING REFRESHER
C - THE LANGUAGE OF UNIX
▸ Fundamental
▸ Easy to learn, simple, powerful
▸ DIY memory management
▸ Tools
▸ Features
▸ Plain old data types
▸ Pointers and addresses
Unix creators Ken Thompson (left, designed
B - 1969, Go - 2007) and Dennis Ritchie
(right, designed C - 1972) of Bell Labs. src: ?
C PROGRAMMING REFRESHER
APPLICATIONS OF C
▸ Performance
▸ Operating systems, drivers
▸ Games
▸ 3d graphics, imaging
▸ Desktop software
▸ File i/o, tools
▸ Most things
Prof. Brian Kernighan (Princeton U.) - co-author
of "K&R C". We will come across his algorithms
work later. src: Wikipedia.
C PROGRAMMING REFRESHER
PORTABILITY
▸ Almost all C also compiles as
▸ C++, objective C
▸ Very similar to
▸ C#, Java, D, PHP, JavaScript...
▸ Somewhat poss. to compile C++ into C
C PROGRAMMING REFRESHER
PRACTISE!
▸ How to get better
▸ read functions' instructions in man pages
▸ don't rely on auto-completion and Q&A websites
▸ watch more exp. people coding
▸ collaborate/share/code reviews/help - don’t be shy
C PROGRAMMING REFRESHER
PRACTISE!
▸ Importance of playing around
▸ What don't you know?
▸ make a list
▸ Ask good questions
C PROGRAMMING REFRESHER
POD TYPES
▸ "plain old data" types
▸ C89 had
▸ unsigned and signed versions
▸ long and short versions
▸ people defined their own
boolean type
▸ C99 and C++ have bool
int
char
float
double
size_t
pointers
typedef int custom_name;
C PROGRAMMING REFRESHER
A STRUCTURED DATA TYPE - ARRAYS
▸ pros
▸ multiple storage
▸ simple
▸ fast - looping over adjacent memory
▸ random access
▸ cons
▸ fixed size at compile time - waste space
▸ elements must be same type
▸ insertion requires shuffling
▸ often come with a count variable to say how much is
used
int my_array[2048];
int sum = 0;
for (int i = 0; i < 2048; i++){
sum += my_array[i];
}
printf("%in", sum);
my_array[238] = 10;
C PROGRAMMING REFRESHER
STRUCT
▸ combine variables into single
custom variable
▸ useful for passing and returning
several variables from function
▸ C++ has classes which are just
structs with some extra properties
▸ typedef usually used to
shorthand your struct as a data
type in C (not needed in C++)
typedef struct My_Combo_Type{
int some_variable;
char some_string[256];
} My_Combo_Type;
My_Combo_Type my_combo;
my_combo.some_variable = 10;
strcpy(my_combo.some_string,
"hello struct");
* there are various ways to initialise a struct
C PROGRAMMING REFRESHER
ADDRESSES
▸ Unique location of each variable
▸ Pass by reference
▸ Ampersand
▸ Dynamic blocks of memory don't
have an associated variable
▸ Refer to by their address
▸ A pointer can store an address
void some_func( int* a );
int my_variable = 0;
some_func( &my_variable );
C PROGRAMMING REFRESHER
POINTERS, DEREFERENCING
▸ Stores memory address (just a
number)
▸ Looks confusing in C
▸ Can point to a pointers address
▸ Dereference to get value stored at
that address
▸ Pointers have a type, for
convenience
▸ Dereferencing a pointer to a struct
remind me to do a diagram
on the whiteboard here
and here
and here
C PROGRAMMING REFRESHER
DYNAMIC MEMORY ALLOCATION
▸ We will use C malloc rather than
C++ new keyword
▸ Know size of data in bytes
▸ sizeof() function
▸ Number of elements
▸ Heap
remind me to do some whiteboard
here
C PROGRAMMING REFRESHER
SIMPLIFY STRUCTURE
▸ Don't get carried away - only solve the problem at hand
▸ Time/cost/benefit
▸ Clarity, KISS
▸ Long functions are fine
▸ Blocks are good section separators { }
▸ Global variables are fine sparingly
▸ Less code, fewer files
▸ Quick and dirty is a great start - you can do a better one next time
C PROGRAMMING REFRESHER
COMPILER SEQUENCE
▸ C is a human language
▸ Pre-processor
▸ Compiler
▸ Assembler
▸ Linker
▸ You can stop compiler at each
stage and inspect the output
▸ Type of issues at each stage src: https://www.cs.cf.ac.uk/Dave/C/node3.html
C PROGRAMMING REFRESHER
ASM INSPECTION
▸ Matt Godbolt's
gcc explorer
https://gcc.godbolt.org/
▸ Insight into what your
code compiles into
▸ How smart is your compiler?
▸ What does optimisation do?
▸ How does inline work?
▸ How efficient is C++ STL vs. our own data structures? Why?
C PROGRAMMING REFRESHER
A PROGRAM'S MEMORY MODEL
▸ reserved system stuff
▸ Stack (frame per function)
▸ Heap (malloc)
▸ BSS (uninitialised statics)
▸ .data (initialised statics)
▸ Text (code)
▸ +dyn libraries loaded in-
between stack and heap
src: http://www.firmcodes.com/memory-layout-c-
program-2/
C PROGRAMMING REFRESHER
THE [FUNCTION CALL] STACK
▸ each function launched is awarded a frame of memory for its
local variables
▸ if that function calls another function inside it - push a new
frame on the stack
▸ when a function ends - pop its frame from stack
▸ most debuggers show you the call stack
▸ on crash can get a "backtrace" or "stack trace"
▸ are huge call stacks of tiny functions bad? - recursive vs loop?
▸ https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/
Mips/stack.html
remind me to draw again
C PROGRAMMING REFRESHER
HEADERS AND >1 FILE
▸ Weakness of C - no packages
▸ #include (cut-pastes in)
▸ to share declarations between files
(otherwise type them at top of every file)
▸ Header guards to avoid "symbol already
defined” circular includes
▸ Using extern and static to share or hide
between files
▸ Usually don't put code instructions in
headers
▸ exceptions
// anton.h - header for anton.c
// written in C99 - Anton Gerdelan - date
#pragma once
#include <stdbool.h>
// concise explanation
int my_other_function(int* addr_of_thing);
extern int g_global_counter_thing;
#include <assert.h>
int g_global_counter_thing;
int my_other_function(int* addr_of_thing) {
assert(addr_of_thing);
*addr_of_thing = *addr_of_thing + 1;
g_global_counter_thing++;
return *addr_of_thing;
}
C PROGRAMMING REFRESHER
MAKEFILES AND BUILD SYSTEMS
▸ Gross
▸ Worth learning
Makefile
▸ IDEs have custom
project files
▸ Meta-build systems
exist
▸ Linking libraries is
painful
C PROGRAMMING REFRESHER
LINKING
▸ Dynamic vs. static libraries
▸ Operating systems all have different formats
▸ dynamic: .so .dll .dylib
▸ static or stubs: .a .lib
▸ System libraries vs. local libraries
▸ We will try to avoid this topic
▸ Linux/Apple may need to link math library explicitly
▸ only if you use functions from math.h
▸ clang -o my_prog main.c -lm
C PROGRAMMING REFRESHER
WHAT TO DO THIS WEEK
▸ Make sure that you can log in to lab computers
▸ Find an easy/working build env.
▸ Visual Studio or another IDE?
▸ Do you know how to step through code with a debugger?
▸ GCC or Clang?
▸ Make sure that you can compile a few simple C examples
▸ Do the warm-up assignment
▸ Let me know if it's too easy/too hard
C PROGRAMMING REFRESHER
TUTORIALS
▸ Tutorial
▸ analysing some code, discussion, solving problems
▸ bring pen+paper (or laptop if you want)
▸ We can modify tutorials to suit needs by request
▸ e.g. what are your concept / tools knowledge gaps?
▸ Assignments
▸ 2-3 weeks each (2x 3hr lab sessions for help/grading)
▸ Know how to do everything - work individually, but not in isolation
▸ Starter code or example in a lecture or tutorial

More Related Content

PDF
BSides Iowa 2018: Windows COM: Red vs Blue
PDF
Compiler design notes phases of compiler
PDF
C Programming Tutorial - www.infomtec.com
PPT
C_Intro.ppt
DOCX
C tutorials
DOCX
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
PPTX
Introduction to C programming
PDF
02 c++g3 d
BSides Iowa 2018: Windows COM: Red vs Blue
Compiler design notes phases of compiler
C Programming Tutorial - www.infomtec.com
C_Intro.ppt
C tutorials
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
Introduction to C programming
02 c++g3 d

Similar to Lecture 2 - C Programming.pdf (20)

PDF
02 c++g3 d (1)
PDF
1 c introduction
PPTX
C++Basics2022.pptx
PDF
GNU Compiler Collection - August 2005
DOC
Introduction-to-C-Part-1 (1).doc
PDF
Introduction-to-C-Part-1.pdf
PDF
c++ referesher 1.pdf
PPT
C tutorial
PDF
Introduction to CMake
PPT
C tutorial
PPT
11 cpp
PPTX
C++ helps you to format the I/O operations like determining the number of dig...
PPTX
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
PPTX
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
PPTX
Introduction-to-C-Part-1.pptx
PPTX
Basics of C Lecture 2[16097].pptx
PPTX
object oriented programming language fundamentals
PDF
Object oriented programming c++
PPTX
Procedure Oriented programming Object Oriented programming Basic Concept of ...
02 c++g3 d (1)
1 c introduction
C++Basics2022.pptx
GNU Compiler Collection - August 2005
Introduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1.pdf
c++ referesher 1.pdf
C tutorial
Introduction to CMake
C tutorial
11 cpp
C++ helps you to format the I/O operations like determining the number of dig...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1.pptx
Basics of C Lecture 2[16097].pptx
object oriented programming language fundamentals
Object oriented programming c++
Procedure Oriented programming Object Oriented programming Basic Concept of ...
Ad

Recently uploaded (20)

PPTX
Presentacion compuuuuuuuuuuuuuuuuuuuuuuu
DOCX
fsdffdghjjgfxfdghjvhjvgfdfcbchghgghgcbjghf
PPT
chapter_1_a.ppthduushshwhwbshshshsbbsbsbsbsh
PDF
Dynamic Checkweighers and Automatic Weighing Machine Solutions
PPTX
5. MEASURE OF INTERIOR AND EXTERIOR- MATATAG CURRICULUM.pptx
PPTX
making presentation that do no stick.pptx
PPT
FABRICATION OF MOS FET BJT DEVICES IN NANOMETER
PPTX
Nanokeyer nano keyekr kano ketkker nano keyer
PPTX
KVL KCL ppt electrical electronics eee tiet
PPTX
Operating System Processes_Scheduler OSS
PPTX
Syllabus Computer Six class curriculum s
PPTX
Embedded for Artificial Intelligence 1.pptx
PPTX
DEATH AUDIT MAY 2025.pptxurjrjejektjtjyjjy
PPTX
material for studying about lift elevators escalation
PPTX
Embeded System for Artificial intelligence 2.pptx
PPTX
Entre CHtzyshshshshshshshzhhzzhhz 4MSt.pptx
PPTX
PLC ANALOGUE DONE BY KISMEC KULIM TD 5 .0
PPT
Hypersensitivity Namisha1111111111-WPS.ppt
PDF
Cableado de Controladores Logicos Programables
PDF
-DIGITAL-INDIA.pdf one of the most prominent
Presentacion compuuuuuuuuuuuuuuuuuuuuuuu
fsdffdghjjgfxfdghjvhjvgfdfcbchghgghgcbjghf
chapter_1_a.ppthduushshwhwbshshshsbbsbsbsbsh
Dynamic Checkweighers and Automatic Weighing Machine Solutions
5. MEASURE OF INTERIOR AND EXTERIOR- MATATAG CURRICULUM.pptx
making presentation that do no stick.pptx
FABRICATION OF MOS FET BJT DEVICES IN NANOMETER
Nanokeyer nano keyekr kano ketkker nano keyer
KVL KCL ppt electrical electronics eee tiet
Operating System Processes_Scheduler OSS
Syllabus Computer Six class curriculum s
Embedded for Artificial Intelligence 1.pptx
DEATH AUDIT MAY 2025.pptxurjrjejektjtjyjjy
material for studying about lift elevators escalation
Embeded System for Artificial intelligence 2.pptx
Entre CHtzyshshshshshshshzhhzzhhz 4MSt.pptx
PLC ANALOGUE DONE BY KISMEC KULIM TD 5 .0
Hypersensitivity Namisha1111111111-WPS.ppt
Cableado de Controladores Logicos Programables
-DIGITAL-INDIA.pdf one of the most prominent
Ad

Lecture 2 - C Programming.pdf

  • 1. C PROGRAMMING DR ANTON GERDELAN <GERDELA@SCSS.TCD.IE>
  • 2. LEAP IN AND TRY THINGS. IF YOU SUCCEED, YOU CAN HAVE ENORMOUS INFLUENCE. IF YOU FAIL, YOU HAVE STILL LEARNED SOMETHING, AND YOUR NEXT ATTEMPT IS SURE TO BE BETTER FOR IT. Brian Kernighan C PROGRAMMING REFRESHER
  • 3. C PROGRAMMING REFRESHER C - THE LANGUAGE OF UNIX ▸ Fundamental ▸ Easy to learn, simple, powerful ▸ DIY memory management ▸ Tools ▸ Features ▸ Plain old data types ▸ Pointers and addresses Unix creators Ken Thompson (left, designed B - 1969, Go - 2007) and Dennis Ritchie (right, designed C - 1972) of Bell Labs. src: ?
  • 4. C PROGRAMMING REFRESHER APPLICATIONS OF C ▸ Performance ▸ Operating systems, drivers ▸ Games ▸ 3d graphics, imaging ▸ Desktop software ▸ File i/o, tools ▸ Most things Prof. Brian Kernighan (Princeton U.) - co-author of "K&R C". We will come across his algorithms work later. src: Wikipedia.
  • 5. C PROGRAMMING REFRESHER PORTABILITY ▸ Almost all C also compiles as ▸ C++, objective C ▸ Very similar to ▸ C#, Java, D, PHP, JavaScript... ▸ Somewhat poss. to compile C++ into C
  • 6. C PROGRAMMING REFRESHER PRACTISE! ▸ How to get better ▸ read functions' instructions in man pages ▸ don't rely on auto-completion and Q&A websites ▸ watch more exp. people coding ▸ collaborate/share/code reviews/help - don’t be shy
  • 7. C PROGRAMMING REFRESHER PRACTISE! ▸ Importance of playing around ▸ What don't you know? ▸ make a list ▸ Ask good questions
  • 8. C PROGRAMMING REFRESHER POD TYPES ▸ "plain old data" types ▸ C89 had ▸ unsigned and signed versions ▸ long and short versions ▸ people defined their own boolean type ▸ C99 and C++ have bool int char float double size_t pointers typedef int custom_name;
  • 9. C PROGRAMMING REFRESHER A STRUCTURED DATA TYPE - ARRAYS ▸ pros ▸ multiple storage ▸ simple ▸ fast - looping over adjacent memory ▸ random access ▸ cons ▸ fixed size at compile time - waste space ▸ elements must be same type ▸ insertion requires shuffling ▸ often come with a count variable to say how much is used int my_array[2048]; int sum = 0; for (int i = 0; i < 2048; i++){ sum += my_array[i]; } printf("%in", sum); my_array[238] = 10;
  • 10. C PROGRAMMING REFRESHER STRUCT ▸ combine variables into single custom variable ▸ useful for passing and returning several variables from function ▸ C++ has classes which are just structs with some extra properties ▸ typedef usually used to shorthand your struct as a data type in C (not needed in C++) typedef struct My_Combo_Type{ int some_variable; char some_string[256]; } My_Combo_Type; My_Combo_Type my_combo; my_combo.some_variable = 10; strcpy(my_combo.some_string, "hello struct"); * there are various ways to initialise a struct
  • 11. C PROGRAMMING REFRESHER ADDRESSES ▸ Unique location of each variable ▸ Pass by reference ▸ Ampersand ▸ Dynamic blocks of memory don't have an associated variable ▸ Refer to by their address ▸ A pointer can store an address void some_func( int* a ); int my_variable = 0; some_func( &my_variable );
  • 12. C PROGRAMMING REFRESHER POINTERS, DEREFERENCING ▸ Stores memory address (just a number) ▸ Looks confusing in C ▸ Can point to a pointers address ▸ Dereference to get value stored at that address ▸ Pointers have a type, for convenience ▸ Dereferencing a pointer to a struct remind me to do a diagram on the whiteboard here and here and here
  • 13. C PROGRAMMING REFRESHER DYNAMIC MEMORY ALLOCATION ▸ We will use C malloc rather than C++ new keyword ▸ Know size of data in bytes ▸ sizeof() function ▸ Number of elements ▸ Heap remind me to do some whiteboard here
  • 14. C PROGRAMMING REFRESHER SIMPLIFY STRUCTURE ▸ Don't get carried away - only solve the problem at hand ▸ Time/cost/benefit ▸ Clarity, KISS ▸ Long functions are fine ▸ Blocks are good section separators { } ▸ Global variables are fine sparingly ▸ Less code, fewer files ▸ Quick and dirty is a great start - you can do a better one next time
  • 15. C PROGRAMMING REFRESHER COMPILER SEQUENCE ▸ C is a human language ▸ Pre-processor ▸ Compiler ▸ Assembler ▸ Linker ▸ You can stop compiler at each stage and inspect the output ▸ Type of issues at each stage src: https://www.cs.cf.ac.uk/Dave/C/node3.html
  • 16. C PROGRAMMING REFRESHER ASM INSPECTION ▸ Matt Godbolt's gcc explorer https://gcc.godbolt.org/ ▸ Insight into what your code compiles into ▸ How smart is your compiler? ▸ What does optimisation do? ▸ How does inline work? ▸ How efficient is C++ STL vs. our own data structures? Why?
  • 17. C PROGRAMMING REFRESHER A PROGRAM'S MEMORY MODEL ▸ reserved system stuff ▸ Stack (frame per function) ▸ Heap (malloc) ▸ BSS (uninitialised statics) ▸ .data (initialised statics) ▸ Text (code) ▸ +dyn libraries loaded in- between stack and heap src: http://www.firmcodes.com/memory-layout-c- program-2/
  • 18. C PROGRAMMING REFRESHER THE [FUNCTION CALL] STACK ▸ each function launched is awarded a frame of memory for its local variables ▸ if that function calls another function inside it - push a new frame on the stack ▸ when a function ends - pop its frame from stack ▸ most debuggers show you the call stack ▸ on crash can get a "backtrace" or "stack trace" ▸ are huge call stacks of tiny functions bad? - recursive vs loop? ▸ https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/ Mips/stack.html remind me to draw again
  • 19. C PROGRAMMING REFRESHER HEADERS AND >1 FILE ▸ Weakness of C - no packages ▸ #include (cut-pastes in) ▸ to share declarations between files (otherwise type them at top of every file) ▸ Header guards to avoid "symbol already defined” circular includes ▸ Using extern and static to share or hide between files ▸ Usually don't put code instructions in headers ▸ exceptions // anton.h - header for anton.c // written in C99 - Anton Gerdelan - date #pragma once #include <stdbool.h> // concise explanation int my_other_function(int* addr_of_thing); extern int g_global_counter_thing; #include <assert.h> int g_global_counter_thing; int my_other_function(int* addr_of_thing) { assert(addr_of_thing); *addr_of_thing = *addr_of_thing + 1; g_global_counter_thing++; return *addr_of_thing; }
  • 20. C PROGRAMMING REFRESHER MAKEFILES AND BUILD SYSTEMS ▸ Gross ▸ Worth learning Makefile ▸ IDEs have custom project files ▸ Meta-build systems exist ▸ Linking libraries is painful
  • 21. C PROGRAMMING REFRESHER LINKING ▸ Dynamic vs. static libraries ▸ Operating systems all have different formats ▸ dynamic: .so .dll .dylib ▸ static or stubs: .a .lib ▸ System libraries vs. local libraries ▸ We will try to avoid this topic ▸ Linux/Apple may need to link math library explicitly ▸ only if you use functions from math.h ▸ clang -o my_prog main.c -lm
  • 22. C PROGRAMMING REFRESHER WHAT TO DO THIS WEEK ▸ Make sure that you can log in to lab computers ▸ Find an easy/working build env. ▸ Visual Studio or another IDE? ▸ Do you know how to step through code with a debugger? ▸ GCC or Clang? ▸ Make sure that you can compile a few simple C examples ▸ Do the warm-up assignment ▸ Let me know if it's too easy/too hard
  • 23. C PROGRAMMING REFRESHER TUTORIALS ▸ Tutorial ▸ analysing some code, discussion, solving problems ▸ bring pen+paper (or laptop if you want) ▸ We can modify tutorials to suit needs by request ▸ e.g. what are your concept / tools knowledge gaps? ▸ Assignments ▸ 2-3 weeks each (2x 3hr lab sessions for help/grading) ▸ Know how to do everything - work individually, but not in isolation ▸ Starter code or example in a lecture or tutorial