The document provides an overview of the C programming language. It begins by explaining that Objective-C extends standard ANSI C with object-oriented capabilities. It then discusses why C remains important today due to its use in libraries, operating systems, and as the base for many other popular languages. The document proceeds to cover basic C concepts like variables, data types, functions, flow control, pointers, memory allocation, and I/O parameters. It emphasizes that C provides high performance with a minimal footprint while abstracting away the CPU and memory.
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
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.
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?
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, …
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);
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…
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";
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 &
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()
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