SlideShare a Scribd company logo
1 of 111
Oh crap! I forgot (or
 never learned) C!
       Chris Adamson
       CodeMash 2010
Objective- C is defined as a small but powerful set of
   extensions to the standard ANSI C language. […]
  Objective-C is designed to give C full object- oriented
programming capabilities, and to do so in a simple and
                   straightforward way.
“Here, John Parker, take
this wheel. It drives just
like a truck.”
“Here, John Parker, take
this wheel. It drives just
like a truck.”


“Good. What is a truck?”
*
**
&
WTF?
Don’t
Panic!
Don’t
   Panic!
You can do this!
1972
1978, 1988
http://
http://
http://
http://
http://www.langpop.com/
Why does C matter
     today?
Libraries with C inside

Linux kernel (C, assembly), GNU libraries (C, C++)
OpenGL, OpenAL, SQLite, PostgreSQL, …
Way more than I can list here:
   http://directory.fsf.org/category/clibs/
Languages that need C

Interpreters and VMs written in C:
   Ruby, PHP, Perl, Java
Typically, you’ll use C to call into native libraries from these
languages (e.g., Java Native Interface)
Even on iPhone

Some essential iPhone libraries are C-only:
   OpenGL, OpenAL
   Core Audio, Core Graphics, Core Foundation
   Keychain, Address Book, System Configuration
C’s descendents

Languages inspired by C or directly based on it are the
dominant languages for systems, application, and mobile
development:
C++, Objective-C, Java, C# [?]
   Can we call these the *C* languages?
Why C?
C’s traits

Minimal: no fluff!
Portable: nearly every OS has a C compiler
Performant!
C performance




http://gmarceau.qc.ca/blog/2009/05/speed-size-and-
               dependability-of.html
C performance




http://gmarceau.qc.ca/blog/2009/05/speed-size-and-
               dependability-of.html
C performance




http://gmarceau.qc.ca/blog/2009/05/speed-size-and-
               dependability-of.html
C performance




http://gmarceau.qc.ca/blog/2009/05/speed-size-and-
               dependability-of.html
C performance




http://gmarceau.qc.ca/blog/2009/05/speed-size-and-
               dependability-of.html
C performance




http://gmarceau.qc.ca/blog/2009/05/speed-size-and-
               dependability-of.html
Is C a high-level
   language?
Abstractions
Abstractions
Abstractions
CPU abstraction


int x = 5;
int y = 10;
int z = x + y;
CPU abstraction

                     .loc   1 38 0
                     movl   $5, -12(%ebp)
                     .loc   1 39 0
int x = 5;           movl   $10, -16(%ebp)
int y = 10;          .loc   1 40 0
int z = x + y;       movl   -16(%ebp), %eax
                     addl   -12(%ebp), %eax
                     movl   %eax, -20(%ebp)

                            Intel x86
CPU abstraction


int x = 5;
int y = 10;
int z = x + y;
CPU abstraction

                     add   r0,   sp, #24
                     add   r3,   sp, #16
int x = 5;           add   r2,   sp, #20
                     ldr   r1,   [r3]
int y = 10;          ldr   r3,   [r2]
int z = x + y;       add   r3,   r1, r3
                     str   r3,   [r0]

                            ARM
Memory abstraction

Memory may be dynamically allocated and freed
   malloc(), free()
No garbage collection or other automated memory
management techniques
   Libraries and later languages add this
“High” or “Low” level

Old CW: Abstracting away the CPU makes you high-level
   Effectively, anything other than assembly was high-level
New CW: Abstracting away the memory makes you high-level
   C in 2010 is what assembly was in 1980
So why should I learn C?

Pro: You may have to use it for something
   Embedded systems, native code calls, highly portable
Con: You probably won’t be as productive
   Lower abstraction cost implies lower abstraction value
How do you (re-)learn C?
C is rarely anyone’s first language
   I learned a variety of BASICs, Pascal, and assembly first
   If you’re at CodeMash, you likely know one or more C-
   inspired languages
       Direct descendants: C++, Java, csh
       Distant relatives: Python, Ruby, other shells
Smoke ‘em if you got ‘em
Your language probably has traits in common with C
   Control structures, parameters and return values, etc.
Your language probably added stuff that C doesn’t have
   Objects
   Garbage Collection
   Closures, type-safety, generics, …
C is so primitive!
We’re gonna learn to hunt
Primitive C
The absolute basics

C source is compiled directly into a machine-executable
binary
As far as the compiler cares, your C program could be one
big listing
Execution starts inside the main() function
Headers and includes

By convention, we use separate header and source files
   Header (.h) includes public information: function names,
   constants, and other stuff needed by callers
   Source (.c, .cpp, .m, .mm) includes implementation code
       Use #include to include header when compiling
“Hello World” in C

  #include <stdio.h>

  int main() {

      printf ("Hello world!");

  }
C expressions

Expression is a combination of operators and operands
   x + 1 has one operator (+) and two operands (x, 1)
Mathematical operators: +, -, *, /, %, >>, <<, >>>
Logical operators: !, &, |, &&, ||, <, >, <=, >=, !=, ?:
   Use parentheses for ordering: a+b*c vs (a+b)*c
C types
Integer types: short, int, long, long long
   int and long may be “unsigned”
Floating-point types: float, double
Other types: char, bool
Absence of type: void
Bit depth of numeric types is undefined
Type conversion
Expressions that combine types implicitly change them
   char, short convert to int
   floats convert to double
   ints convert to long
   unsigned becomes signed
   all other cases: everything’s an int
Assignment
Declare a variable of a type, then assign its value as the
result of an expression

                 int x;
                 x = 3;

                 x = x + 1
                 x += 1;
                 x++;
Assignment from functions
Can also use a function call to assign a value
Can combine these

          int x;
          x = abs (rand() % 5);
Creating a function
 Declare return type, name, parameter types and names


double circumference (double r) {
    return 2 * 3.14159 * r;
}
Variable scope
C variables use lexical scope: only available within the
function in which they’re declared
   Variables with same name in different scope are different
   variables
Variables declared outside the scope of any function are
“global variables”, and are available anywhere
   Try not to use them much, if at all
Pass by value
What is the value of y?

         int addOne (int x) {
           return x+1;
         }

         int y = 0;
         int z = addOne (y);
Pass by value
What is the value of y?

         int addOne (int x) {
           return x+1;
         }

         int y = 0;
         int z = addOne (y);


y is still 0. The function gets y’s value (0), not the y
variable itself
Flow Control: if-else
    if (expression)
      // execute statement if true
    else
      // execute statement if false


“true” means “non-zero”
Executes only one statement for each branch; use curly-
braces to do more
Flow-control: switch
switch (expression) {
  case value1:
      // statements
      break;
  case value2:
      // statements
      break;
  // other cases
  default:
      // statements execute in any case
}
Flow-control: while

     while (expression)
     // statement

     do
     // statement
     while (expression);
Flow-control: for

for (initExpression;
      continueExpression;
      countingExpression)
// statement
Flow-control: break

break terminates innermost for, while, do, or switch
return exits from a function, with a value if function declares
one
goto jumps to a labelled line of code
   “Go To statement considered harmful”, 1968
Complex types
enums
 enum {HEARTS, DIAMONDS, CLUBS, SPADES};

A list of constant int values
Starts at 0 and increments, unless you assign specific values
with =
Alternative: use #define preprocessor directive

           #define HEARTS 1
           #define DIAMONDS 2
New types: typedef

    Allows you to define new type names for variables
    By convention, typedef names are capitalized

typedef enum {HEARTS, DIAMONDS, CLUBS, SPADES} SuitType;

int main() {
  SuitType suit = DIAMONDS;
}
Structs

Creates “structure” consisting of several named members of
various types
Access members with dot operator
Really tempting to call it an “object”, but…
Structs aren’t objects
Structs aren’t objects

    struct CGPoint {
       CGFloat x;
       CGFloat y;
    };
    typedef struct CGPoint CGPoint;
Structs aren’t objects
Structs aren’t objects
  void addToPointX (CGPoint aPoint) {
    aPoint.x += 10;
  }
Structs aren’t objects
  void addToPointX (CGPoint aPoint) {
    aPoint.x += 10;
  }

  CGPoint point;
  point.x=0;
  point.y=0;
  addToPointX (point);
Structs aren’t objects
     void addToPointX (CGPoint aPoint) {
       aPoint.x += 10;
     }

     CGPoint point;
     point.x=0;
     point.y=0;
     addToPointX (point);

point.x is still 0, because the whole CGPoint is a value,
                        not an object
Arrays
Indexed access to multiple instances of a type
Declare with [] and size of array
Access an index with [index]
   First member is index=0

       Card deck[52];
       Card topCard = deck[0];
Character arrays / strings
An array of type char is a string
   Terminated by a null character (/0)
Can declare literals with “” operator
Conveys no information about encoding, typically assumed
to be ASCII

 char confName[] = "CodeMash";
This is where it gets
        scary
Arrays are syntactic sugar

Array is just a reference to a location in memory
Index is an offset
   No bounds checking!
Pointers
A pointer is literally a memory address, interpreted as a
reference to a variable at that memory address
Indicated with the * character
Pointers
A pointer is literally a memory address, interpreted as a
reference to a variable at that memory address
Indicated with the * character


 char confName[] = "CodeMash";
Pointers
A pointer is literally a memory address, interpreted as a
reference to a variable at that memory address
Indicated with the * character
Pointers
A pointer is literally a memory address, interpreted as a
reference to a variable at that memory address
Indicated with the * character


 char *confName = "CodeMash";
Using pointers
A pointer to a variable is used like any other variable of that
type
Access to members of a pointed-to struct use the -> operator
A function that takes a pointer parameter or returns a
pointer declares * on the type
To refer to the address of a pointer, use &
Pointer example
Pointer example
void reallyAddToPointX (CGPoint *aPoint) {
  aPoint->x += 10;
}
Pointer example
void reallyAddToPointX (CGPoint *aPoint) {
  aPoint->x += 10;
}

CGPoint point;
point.x=0;
point.y=0;
reallyAddToPointX (&point);
Pointer example
void reallyAddToPointX (CGPoint *aPoint) {
  aPoint->x += 10;
}

CGPoint point;
point.x=0;
point.y=0;
reallyAddToPointX (&point);


             point.x is now 10.0
Allocating memory

Allocate memory with malloc()
   The amount you need can be determined with sizeof()
   Return value is a pointer to allocated memory
Release memory with free()
malloc() example
CGPoint point;
point.x=0;
point.y=0;
reallyAddToPointX (&point);
malloc() example
CGPoint point;
point.x=0;
point.y=0;
reallyAddToPointX (&point);

CGPoint *point = malloc(sizeof(CGPoint));
point->x=0;
point->y=0;
reallyAddToPointX (point);
malloc() example
CGPoint point;
point.x=0;
point.y=0;
reallyAddToPointX (&point);

CGPoint *point = malloc(sizeof(CGPoint));
point->x=0;
point->y=0;
reallyAddToPointX (point);
free (point);
How to crash instantly

Use a bogus address in a pointer
         CGPoint *point = 42;
         point->x = 0;
How to crash instantly

      Use a bogus address in a pointer
                  CGPoint *point = 42;
                  point->x = 0;
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x000000000000002a
Crashed Thread: 0 Dispatch queue: com.apple.main-thread

Application Specific Information:
iPhone Simulator 3.1 (139.1), iPhone OS 3.1.2 (7D11)

Thread 0 Crashed: Dispatch queue: com.apple.main-thread
0   CGPointCheck                   0x00002854 -[CGPointCheckViewController
viewDidLoad] + 72 (CGPointCheckViewController.m:53)
More memory functions

Copy blocks of memory with memcpy()
Set a block of memory with memset()
   Often used to “zero out” a buffer
Address arithmetic
Some memory functions require you to compute memory
locations manually
   Assume array a of type t
   Index n is at a + (n * sizeof(t))
Address arithmetic
  Some memory functions require you to compute memory
  locations manually
     Assume array a of type t
     Index n is at a + (n * sizeof(t))

memcpy(ioData->mBuffers[currentBuffer].mData +
         (currentFrame * 4) + (currentChannel*2),
   &sample,
   sizeof(AudioSampleType));
I/O parameters
C’s version of multiple return values
You pass in a pointer, it gets populated when function
returns
    OSStatus AudioUnitGetProperty (
       AudioUnit            inUnit,
       AudioUnitPropertyID inID,
       AudioUnitScope       inScope,
       AudioUnitElement     inElement,
       void                 *outData,
       UInt32               *ioDataSize
    );
That’s It
Things to take away
C is still popular for good reasons
   C’s performance and portability are building blocks for
   languages and libraries
   Lingua franca: everybody used to know it. Maybe
   everyone still should.
Thinking about memory can be a good thing!
When you have questions

Kernighan & Ritchie, The C Programming
Language, Prentice-Hall, 1988 (yes, really)
comp.lang.c
stackoverflow.com
Sample code!
Or just bug me

Web: http://www.subfurther.com
Blog: http://www.subfurther.com/blog
E-mail: invalidname@gmail.com
Twitter: @invalidname

More Related Content

What's hot

What's hot (20)

C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Computer Programming- Lecture 3
Computer Programming- Lecture 3Computer Programming- Lecture 3
Computer Programming- Lecture 3
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
C Theory
C TheoryC Theory
C Theory
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
C
CC
C
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
 
C tutorial
C tutorialC tutorial
C tutorial
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 

Similar to Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]

Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xiiSyed Zaid Irshad
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxKrishanPalSingh39
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance levelsajjad ali khan
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxWatchDog13
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesSukhpreetSingh519414
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxLikhil181
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing TutorialMahira Banu
 

Similar to Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010] (20)

C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
C++ language
C++ languageC++ language
C++ language
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
 
C tutorial
C tutorialC tutorial
C tutorial
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
c_tutorial_2.ppt
c_tutorial_2.pptc_tutorial_2.ppt
c_tutorial_2.ppt
 
C intro
C introC intro
C intro
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
c.ppt
c.pptc.ppt
c.ppt
 

More from Chris Adamson

Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)Chris Adamson
 
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)Chris Adamson
 
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)Chris Adamson
 
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...Chris Adamson
 
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineCocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineChris Adamson
 
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineForward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineChris Adamson
 
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...Chris Adamson
 
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)Chris Adamson
 
Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)Chris Adamson
 
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)Chris Adamson
 
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)Chris Adamson
 
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)Chris Adamson
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Chris Adamson
 
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014Chris Adamson
 
Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Chris Adamson
 
Stupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasStupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasChris Adamson
 
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Chris Adamson
 
Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)Chris Adamson
 
Introduction to the Roku SDK
Introduction to the Roku SDKIntroduction to the Roku SDK
Introduction to the Roku SDKChris Adamson
 

More from Chris Adamson (20)

Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
 
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
 
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
 
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
 
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineCocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
 
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineForward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
 
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
 
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
 
Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)
 
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
 
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
 
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
 
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
 
Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014
 
Stupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasStupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las Vegas
 
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
 
Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)
 
Stupid Video Tricks
Stupid Video TricksStupid Video Tricks
Stupid Video Tricks
 
Introduction to the Roku SDK
Introduction to the Roku SDKIntroduction to the Roku SDK
Introduction to the Roku SDK
 

Recently uploaded

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Recently uploaded (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]

  • 1. Oh crap! I forgot (or never learned) C! Chris Adamson CodeMash 2010
  • 2.
  • 3. Objective- C is defined as a small but powerful set of extensions to the standard ANSI C language. […] Objective-C is designed to give C full object- oriented programming capabilities, and to do so in a simple and straightforward way.
  • 4.
  • 5. “Here, John Parker, take this wheel. It drives just like a truck.”
  • 6. “Here, John Parker, take this wheel. It drives just like a truck.” “Good. What is a truck?”
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15. *
  • 16. **
  • 17. &
  • 18. WTF?
  • 20. Don’t Panic! You can do this!
  • 21. 1972
  • 23.
  • 29. Why does C matter today?
  • 30. Libraries with C inside Linux kernel (C, assembly), GNU libraries (C, C++) OpenGL, OpenAL, SQLite, PostgreSQL, … Way more than I can list here: http://directory.fsf.org/category/clibs/
  • 31. Languages that need C Interpreters and VMs written in C: Ruby, PHP, Perl, Java Typically, you’ll use C to call into native libraries from these languages (e.g., Java Native Interface)
  • 32. Even on iPhone Some essential iPhone libraries are C-only: OpenGL, OpenAL Core Audio, Core Graphics, Core Foundation Keychain, Address Book, System Configuration
  • 33. C’s descendents Languages inspired by C or directly based on it are the dominant languages for systems, application, and mobile development: C++, Objective-C, Java, C# [?] Can we call these the *C* languages?
  • 35. C’s traits Minimal: no fluff! Portable: nearly every OS has a C compiler Performant!
  • 42. Is C a high-level language?
  • 46. CPU abstraction int x = 5; int y = 10; int z = x + y;
  • 47. CPU abstraction .loc 1 38 0 movl $5, -12(%ebp) .loc 1 39 0 int x = 5; movl $10, -16(%ebp) int y = 10; .loc 1 40 0 int z = x + y; movl -16(%ebp), %eax addl -12(%ebp), %eax movl %eax, -20(%ebp) Intel x86
  • 48. CPU abstraction int x = 5; int y = 10; int z = x + y;
  • 49. CPU abstraction add r0, sp, #24 add r3, sp, #16 int x = 5; add r2, sp, #20 ldr r1, [r3] int y = 10; ldr r3, [r2] int z = x + y; add r3, r1, r3 str r3, [r0] ARM
  • 50. Memory abstraction Memory may be dynamically allocated and freed malloc(), free() No garbage collection or other automated memory management techniques Libraries and later languages add this
  • 51. “High” or “Low” level Old CW: Abstracting away the CPU makes you high-level Effectively, anything other than assembly was high-level New CW: Abstracting away the memory makes you high-level C in 2010 is what assembly was in 1980
  • 52. So why should I learn C? Pro: You may have to use it for something Embedded systems, native code calls, highly portable Con: You probably won’t be as productive Lower abstraction cost implies lower abstraction value
  • 53. How do you (re-)learn C? C is rarely anyone’s first language I learned a variety of BASICs, Pascal, and assembly first If you’re at CodeMash, you likely know one or more C- inspired languages Direct descendants: C++, Java, csh Distant relatives: Python, Ruby, other shells
  • 54. Smoke ‘em if you got ‘em Your language probably has traits in common with C Control structures, parameters and return values, etc. Your language probably added stuff that C doesn’t have Objects Garbage Collection Closures, type-safety, generics, …
  • 55. C is so primitive!
  • 58. The absolute basics C source is compiled directly into a machine-executable binary As far as the compiler cares, your C program could be one big listing Execution starts inside the main() function
  • 59. Headers and includes By convention, we use separate header and source files Header (.h) includes public information: function names, constants, and other stuff needed by callers Source (.c, .cpp, .m, .mm) includes implementation code Use #include to include header when compiling
  • 60. “Hello World” in C #include <stdio.h> int main() { printf ("Hello world!"); }
  • 61. C expressions Expression is a combination of operators and operands x + 1 has one operator (+) and two operands (x, 1) Mathematical operators: +, -, *, /, %, >>, <<, >>> Logical operators: !, &, |, &&, ||, <, >, <=, >=, !=, ?: Use parentheses for ordering: a+b*c vs (a+b)*c
  • 62. C types Integer types: short, int, long, long long int and long may be “unsigned” Floating-point types: float, double Other types: char, bool Absence of type: void Bit depth of numeric types is undefined
  • 63. Type conversion Expressions that combine types implicitly change them char, short convert to int floats convert to double ints convert to long unsigned becomes signed all other cases: everything’s an int
  • 64. Assignment Declare a variable of a type, then assign its value as the result of an expression int x; x = 3; x = x + 1 x += 1; x++;
  • 65. Assignment from functions Can also use a function call to assign a value Can combine these int x; x = abs (rand() % 5);
  • 66. Creating a function Declare return type, name, parameter types and names double circumference (double r) { return 2 * 3.14159 * r; }
  • 67. Variable scope C variables use lexical scope: only available within the function in which they’re declared Variables with same name in different scope are different variables Variables declared outside the scope of any function are “global variables”, and are available anywhere Try not to use them much, if at all
  • 68. Pass by value What is the value of y? int addOne (int x) { return x+1; } int y = 0; int z = addOne (y);
  • 69. Pass by value What is the value of y? int addOne (int x) { return x+1; } int y = 0; int z = addOne (y); y is still 0. The function gets y’s value (0), not the y variable itself
  • 70. Flow Control: if-else if (expression) // execute statement if true else // execute statement if false “true” means “non-zero” Executes only one statement for each branch; use curly- braces to do more
  • 71. Flow-control: switch switch (expression) { case value1: // statements break; case value2: // statements break; // other cases default: // statements execute in any case }
  • 72. Flow-control: while while (expression) // statement do // statement while (expression);
  • 73. Flow-control: for for (initExpression; continueExpression; countingExpression) // statement
  • 74. Flow-control: break break terminates innermost for, while, do, or switch return exits from a function, with a value if function declares one goto jumps to a labelled line of code “Go To statement considered harmful”, 1968
  • 76. enums enum {HEARTS, DIAMONDS, CLUBS, SPADES}; A list of constant int values Starts at 0 and increments, unless you assign specific values with = Alternative: use #define preprocessor directive #define HEARTS 1 #define DIAMONDS 2
  • 77. New types: typedef Allows you to define new type names for variables By convention, typedef names are capitalized typedef enum {HEARTS, DIAMONDS, CLUBS, SPADES} SuitType; int main() { SuitType suit = DIAMONDS; }
  • 78. Structs Creates “structure” consisting of several named members of various types Access members with dot operator Really tempting to call it an “object”, but…
  • 80. Structs aren’t objects struct CGPoint { CGFloat x; CGFloat y; }; typedef struct CGPoint CGPoint;
  • 82. Structs aren’t objects void addToPointX (CGPoint aPoint) { aPoint.x += 10; }
  • 83. Structs aren’t objects void addToPointX (CGPoint aPoint) { aPoint.x += 10; } CGPoint point; point.x=0; point.y=0; addToPointX (point);
  • 84. Structs aren’t objects void addToPointX (CGPoint aPoint) { aPoint.x += 10; } CGPoint point; point.x=0; point.y=0; addToPointX (point); point.x is still 0, because the whole CGPoint is a value, not an object
  • 85. Arrays Indexed access to multiple instances of a type Declare with [] and size of array Access an index with [index] First member is index=0 Card deck[52]; Card topCard = deck[0];
  • 86. Character arrays / strings An array of type char is a string Terminated by a null character (/0) Can declare literals with “” operator Conveys no information about encoding, typically assumed to be ASCII char confName[] = "CodeMash";
  • 87. This is where it gets scary
  • 88. Arrays are syntactic sugar Array is just a reference to a location in memory Index is an offset No bounds checking!
  • 89. Pointers A pointer is literally a memory address, interpreted as a reference to a variable at that memory address Indicated with the * character
  • 90. Pointers A pointer is literally a memory address, interpreted as a reference to a variable at that memory address Indicated with the * character char confName[] = "CodeMash";
  • 91. Pointers A pointer is literally a memory address, interpreted as a reference to a variable at that memory address Indicated with the * character
  • 92. Pointers A pointer is literally a memory address, interpreted as a reference to a variable at that memory address Indicated with the * character char *confName = "CodeMash";
  • 93. Using pointers A pointer to a variable is used like any other variable of that type Access to members of a pointed-to struct use the -> operator A function that takes a pointer parameter or returns a pointer declares * on the type To refer to the address of a pointer, use &
  • 95. Pointer example void reallyAddToPointX (CGPoint *aPoint) { aPoint->x += 10; }
  • 96. Pointer example void reallyAddToPointX (CGPoint *aPoint) { aPoint->x += 10; } CGPoint point; point.x=0; point.y=0; reallyAddToPointX (&point);
  • 97. Pointer example void reallyAddToPointX (CGPoint *aPoint) { aPoint->x += 10; } CGPoint point; point.x=0; point.y=0; reallyAddToPointX (&point); point.x is now 10.0
  • 98. Allocating memory Allocate memory with malloc() The amount you need can be determined with sizeof() Return value is a pointer to allocated memory Release memory with free()
  • 100. malloc() example CGPoint point; point.x=0; point.y=0; reallyAddToPointX (&point); CGPoint *point = malloc(sizeof(CGPoint)); point->x=0; point->y=0; reallyAddToPointX (point);
  • 101. malloc() example CGPoint point; point.x=0; point.y=0; reallyAddToPointX (&point); CGPoint *point = malloc(sizeof(CGPoint)); point->x=0; point->y=0; reallyAddToPointX (point); free (point);
  • 102. How to crash instantly Use a bogus address in a pointer CGPoint *point = 42; point->x = 0;
  • 103. How to crash instantly Use a bogus address in a pointer CGPoint *point = 42; point->x = 0; Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x000000000000002a Crashed Thread: 0 Dispatch queue: com.apple.main-thread Application Specific Information: iPhone Simulator 3.1 (139.1), iPhone OS 3.1.2 (7D11) Thread 0 Crashed: Dispatch queue: com.apple.main-thread 0 CGPointCheck 0x00002854 -[CGPointCheckViewController viewDidLoad] + 72 (CGPointCheckViewController.m:53)
  • 104. More memory functions Copy blocks of memory with memcpy() Set a block of memory with memset() Often used to “zero out” a buffer
  • 105. Address arithmetic Some memory functions require you to compute memory locations manually Assume array a of type t Index n is at a + (n * sizeof(t))
  • 106. Address arithmetic Some memory functions require you to compute memory locations manually Assume array a of type t Index n is at a + (n * sizeof(t)) memcpy(ioData->mBuffers[currentBuffer].mData + (currentFrame * 4) + (currentChannel*2), &sample, sizeof(AudioSampleType));
  • 107. I/O parameters C’s version of multiple return values You pass in a pointer, it gets populated when function returns OSStatus AudioUnitGetProperty ( AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void *outData, UInt32 *ioDataSize );
  • 109. Things to take away C is still popular for good reasons C’s performance and portability are building blocks for languages and libraries Lingua franca: everybody used to know it. Maybe everyone still should. Thinking about memory can be a good thing!
  • 110. When you have questions Kernighan & Ritchie, The C Programming Language, Prentice-Hall, 1988 (yes, really) comp.lang.c stackoverflow.com Sample code!
  • 111. Or just bug me Web: http://www.subfurther.com Blog: http://www.subfurther.com/blog E-mail: invalidname@gmail.com Twitter: @invalidname