• Save
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

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

on

  • 6,201 views

Abstract: Chances are you code in a language that's either descended from C, inspired by C, or run in an interpreter that itself is written in C. Still... do you actually know how to code in C? ...

Abstract: Chances are you code in a language that's either descended from C, inspired by C, or run in an interpreter that itself is written in C. Still... do you actually know how to code in C? Despite its long-standing position as a sort of "lingua franca", an agreed-upon common language, more and more developers are putting together successful, satisfying careers, without ever learning this seminal language. But what if you have to call into C code from your favorite scripting language, or use APIs like OpenGL that are written to be called from C? Many developers find C very challenging, particularly its manual memory-management and other low-level concerns. In this session, we'll show you why you shouldn't be afraid of C, how you can use the skills you already have from the languages you code in today, and how to master structs, enums, typedefs, malloc(), free(), and the rest of C's sharp edges. Examples will be from the point-of-view of the C-skewing iPhone SDK, but will be designed to be broadly applicable and platform-agnostic.

Statistics

Views

Total Views
6,201
Views on SlideShare
6,152
Embed Views
49

Actions

Likes
12
Downloads
0
Comments
1

5 Embeds 49

http://www.slideshare.net 21
http://skillschool.co.in 18
http://www.skillschool.co.in 6
http://203.144.133.44 2
http://192.168.6.52 2

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Ugh. This is exactly the kind of thing I need offline. Too bad it can't be downloaded. Looks great, but I'd be using it while away from networks.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

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

  • 1. Oh crap! I forgot (or never learned) C! Chris Adamson CodeMash 2010
  • 2. 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.
  • 3. “Here, John Parker, take this wheel. It drives just like a truck.”
  • 4. “Here, John Parker, take this wheel. It drives just like a truck.” “Good. What is a truck?”
  • 5. *
  • 6. **
  • 7. &
  • 8. WTF?
  • 9. Don’t Panic!
  • 10. Don’t Panic! You can do this!
  • 11. 1972
  • 12. 1978, 1988
  • 13. http://
  • 14. http://
  • 15. http://
  • 16. http://
  • 17. http://www.langpop.com/
  • 18. Why does C matter today?
  • 19. 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/
  • 20. 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)
  • 21. Even on iPhone Some essential iPhone libraries are C-only: OpenGL, OpenAL Core Audio, Core Graphics, Core Foundation Keychain, Address Book, System Configuration
  • 22. 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?
  • 23. Why C?
  • 24. C’s traits Minimal: no fluff! Portable: nearly every OS has a C compiler Performant!
  • 25. C performance http://gmarceau.qc.ca/blog/2009/05/speed-size-and- dependability-of.html
  • 26. C performance http://gmarceau.qc.ca/blog/2009/05/speed-size-and- dependability-of.html
  • 27. C performance http://gmarceau.qc.ca/blog/2009/05/speed-size-and- dependability-of.html
  • 28. C performance http://gmarceau.qc.ca/blog/2009/05/speed-size-and- dependability-of.html
  • 29. C performance http://gmarceau.qc.ca/blog/2009/05/speed-size-and- dependability-of.html
  • 30. C performance http://gmarceau.qc.ca/blog/2009/05/speed-size-and- dependability-of.html
  • 31. Is C a high-level language?
  • 32. Abstractions
  • 33. Abstractions
  • 34. Abstractions
  • 35. CPU abstraction int x = 5; int y = 10; int z = x + y;
  • 36. 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
  • 37. CPU abstraction int x = 5; int y = 10; int z = x + y;
  • 38. 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
  • 39. 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
  • 40. “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
  • 41. 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
  • 42. 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
  • 43. 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, …
  • 44. C is so primitive!
  • 45. We’re gonna learn to hunt
  • 46. Primitive C
  • 47. 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
  • 48. 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
  • 49. “Hello World” in C #include <stdio.h> int main() { printf ("Hello world!"); }
  • 50. 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
  • 51. 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
  • 52. 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
  • 53. 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++;
  • 54. Assignment from functions Can also use a function call to assign a value Can combine these int x; x = abs (rand() % 5);
  • 55. Creating a function Declare return type, name, parameter types and names double circumference (double r) { return 2 * 3.14159 * r; }
  • 56. 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
  • 57. Pass by value What is the value of y? int addOne (int x) { return x+1; } int y = 0; int z = addOne (y);
  • 58. 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
  • 59. 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
  • 60. Flow-control: switch switch (expression) { case value1: // statements break; case value2: // statements break; // other cases default: // statements execute in any case }
  • 61. Flow-control: while while (expression) // statement do // statement while (expression);
  • 62. Flow-control: for for (initExpression; continueExpression; countingExpression) // statement
  • 63. 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
  • 64. Complex types
  • 65. 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
  • 66. 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; }
  • 67. Structs Creates “structure” consisting of several named members of various types Access members with dot operator Really tempting to call it an “object”, but…
  • 68. Structs aren’t objects
  • 69. Structs aren’t objects struct CGPoint { CGFloat x; CGFloat y; }; typedef struct CGPoint CGPoint;
  • 70. Structs aren’t objects
  • 71. Structs aren’t objects void addToPointX (CGPoint aPoint) { aPoint.x += 10; }
  • 72. Structs aren’t objects void addToPointX (CGPoint aPoint) { aPoint.x += 10; } CGPoint point; point.x=0; point.y=0; addToPointX (point);
  • 73. 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
  • 74. 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];
  • 75. 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";
  • 76. This is where it gets scary
  • 77. Arrays are syntactic sugar Array is just a reference to a location in memory Index is an offset No bounds checking!
  • 78. Pointers A pointer is literally a memory address, interpreted as a reference to a variable at that memory address Indicated with the * character
  • 79. 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";
  • 80. Pointers A pointer is literally a memory address, interpreted as a reference to a variable at that memory address Indicated with the * character
  • 81. 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";
  • 82. 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 &
  • 83. Pointer example
  • 84. Pointer example void reallyAddToPointX (CGPoint *aPoint) { aPoint->x += 10; }
  • 85. Pointer example void reallyAddToPointX (CGPoint *aPoint) { aPoint->x += 10; } CGPoint point; point.x=0; point.y=0; reallyAddToPointX (&point);
  • 86. 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
  • 87. 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()
  • 88. malloc() example CGPoint point; point.x=0; point.y=0; reallyAddToPointX (&point);
  • 89. 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);
  • 90. 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);
  • 91. How to crash instantly Use a bogus address in a pointer CGPoint *point = 42; point->x = 0;
  • 92. 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)
  • 93. More memory functions Copy blocks of memory with memcpy() Set a block of memory with memset() Often used to “zero out” a buffer
  • 94. 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))
  • 95. 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));
  • 96. 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 );
  • 97. That’s It
  • 98. 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!
  • 99. When you have questions Kernighan & Ritchie, The C Programming Language, Prentice-Hall, 1988 (yes, really) comp.lang.c stackoverflow.com Sample code!
  • 100. Or just bug me Web: http://www.subfurther.com Blog: http://www.subfurther.com/blog E-mail: invalidname@gmail.com Twitter: @invalidname