1 / 63

The Art of C Programming

The Art of C Programming. WANG Cong xiyou.wangcong@gmail.com. To C or not to C? --Eric S. Raymond. Why this lecture?. C is both fun and tricky to play with. Show the art of programming with C. Most of you didn't learn C well enough. Some of you often use C in many wrong ways.

zasha
Download Presentation

The Art of C Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The Art of C Programming WANG Congxiyou.wangcong@gmail.com

  2. To C or not to C? --Eric S. Raymond

  3. Why this lecture? • C is both fun and tricky to play with. • Show the art of programming with C. • Most of you didn't learn C well enough. • Some of you often use C in many wrong ways. • I am writing a book that has the same name. (So this is also a good chance to find a co-author.)

  4. What's NOT about? • C++ is _another_ programming language, so it's off-topic here. • The basic knowledge of C, which I assume you already know. ;-) • Why I didn't choose VC or TC? Or why gcc? • Software engineering theory is another topic. • Algorithms.

  5. What's about? • Why computer programming is an art. • How to write bug-free C programs. • The international standard of C. • How to wirte obfuscated C code. • How to become a language lawyer of C.

  6. Warmups Section Zero

  7. Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration. • —Stan Kelly-Bootle

  8. 1 or 0? • 1? sizeof(s)/sizeof(s[0]) is the last index of foo_t s[M]. What's more, we count from 1, right? ;) • 0? The 2^N numbers occupy N bits exactly. What's more, memory starts at 0x00000000. • Off-by-one? Try want_array_argument(&a[-1]);?

  9. Arrays VS Pointers • You know arrays are NOT pointers, of course. • Array name can't be used as l-values, while pointers can. It's obvious. • But when arrays ARE pointers? ECP, page 208. • C has multidimensional arrays? Or they are just arrays of arrays?

  10. Mistakes you ever made • void main();? Wrong! Do remember main() only has two portable prototype: int main(void) or int main(int argc, char *argv[]). • You often forgot to check the return value of malloc(), fopen() etc., right? • - if (! card_alloc & (1 << i)) + if (!(card_alloc & (1 << i)))

  11. You often overdo this kind of work: int *p = (int*)malloc(...); • Poorly, some of you dare use gets(). Ha-ha... you will win WORST C program award from me. • You are taught that goto is absolutely harmful, right? • clrscr(), getch() or getche() is your favourite?

  12. You are afraid of these? • typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler); • char *(*c[10])(int **p); is also easy, right? • Then this one? (*(void(*)())0)();

  13. Then these? • int i = 5; i = ++i + ++i; So, i=? This behavior is undefined! • int a=1, b=2, y=0; y = a++ + ++b; Then y=? Illegal. See C99 6.3.2.1.

  14. Art of Programming Section One

  15. (program(computers) == *art) ? so : what

  16. Why Art?

  17. The Beautiful C Code int a=10000,b,c=2800,d,e,f[2801],g; main(){ for(;b-c;)f[b++]=a/5; for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a) for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}

  18. char *f="char *f= %c%s%c;main(){printf(f,34,f,34,10);} %c"; main(){printf(f,34,f,34,10);} Quine

  19. A Puzzle • Print the numbers between 1 and 1000. • Add a rule: Don't use any loops. • Add another rule: No recursions. • We can't do that? OK. Please look at this one.

  20. #include <stdio.h> • #define A(x) x;x;x;x;x;x;x;x;x;x; • int main (void){ • int n = 1; • A(A(A(printf ("%d ", n++)))); • return 0; • }

  21. Another Puzzle • Give you the prototype of the function: int p(int i, int N);, use it to print the numbers from i up to N and then down to i again, one number per line.

  22. Add a rule: Don't use those keywords: do, while, for, switch, case, break, continue, goto, if. • Add another rule: Don't use ':?'. • The last rule: You can only use ONE statement! • Got it? Or impossible?

  23. int p(int i, int N) • { • return (i<N && printf("%d\n", i) && !p(i+1, N)) • || printf("%d\n", i); • }

  24. Art is Here • It is a product of human skill and imagination. • It is intended to communicate in addition to any other function it may have. • There is an aesthetic associated with it. • The aesthetics and ideas communicated transcend the particulars of an individual work.

  25. Artist • “A programmer who subconsciously views himself as an artist will enjoy what he does and will do it better.” -- Donald E. Knuth • “What hackers and painters have in common is that they're both makers. What hackers and painters are trying to do is make good things.” --Paul Graham

  26. “I’m with Knuth’s definition (or use) of the word art. To me, it relates strongly to creativity, which is very important for my line of work. If there was no art in it, it wouldn’t be any fun, and then I wouldn’t still be doing it after 30 years.” -- Guido van Rossum • When done right, art and craft blends seamlessly. That’s the view of several schools of design, though of course not the view of people into “art as provocation.” -- Bjarne Stroustrup

  27. Details & Tricks Section Two

  28. Library functions • malloc(0)/realloc(p, 0) is implementation defined. • realloc(NULL, N) equals to malloc(N). • free(NULL) is safe. Do you know? • Free a space that has already been freed is undefined behavior.

  29. sprintf • sprintf() may be unsafe for you, are you really sure you have enough memory to hold them? • sprintf(buf,"Errors in line %d, %u is %s.",line,err,msg); • What's more, you can't check whether your sprintf() is alright.

  30. strncpy/strncat • strcpy/strcat is unsafe, so these two are safe? • strncpy may be can't end your string! • strncat may be misunderstood by you. • Try strlcpy and strlcat.

  31. strtok • Never use this function, like gets(). • It uses some internal static variables, so it's NOT reentrant and NOT thread-safe. • Try strtok_r() instead. • Most POSIX functions are reentrant.

  32. Head files • Avoid your head files being included multi-times. #ifndef _STDIO_H #define _STDIO_H /*omit other code*/ #endif

  33. You should NOT put the definitions of variables or functions in headers. • You can put the definition of a struct/union, the const values and the inline functions in headers. • You should not #include a .c file like the head files.

  34. Macros are evil? • Yes. It makes debugging hard, it is not type-safe and it often has side-effect! • NO! • Without macros, debugging is hard, for example, assert(), __LINE__, __FILE__.

  35. Macros can do as well as templates of C++, try typeof of gcc. (Yes, standard C can't do that.) • You should avoid side-effect anywhere, NOT just in macros. • Macros can be used beautifully as what we will see.

  36. Macro-like functions • do{...}while(0) is your friend: #define init_wait(wait) \ do { \ (wait)->private = current; \ } while (0)

  37. #define foo(wq, condition) \ • ({ \ • int __ret = 0; \ • if (!(condition)) \ • __foo(wq, condition, __ret); \ • __ret; \ • })

  38. Container • Get the container: #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr);\ (type *)( (char *)__mptr - offsetof(type,member) );})

  39. Type checker #define typecheck(type,x) \ ({ type __dummy; \ typeof(x) __dummy2; \ (void)(&__dummy == &__dummy2); \ 1; \ })

  40. Duff's Device

  41. Quake 3

  42. Section Three Standard

  43. What Standard? • C89(C90), the earliest C standard, ISO/IEC 9899:1990 • C95(C94), AMD1, wide and multibyte characters support • C99, ISO/IEC 9899:1999, the latest • Available here: http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1124.pdf • Or buy the book: The C Standard

  44. C Standard Committee

  45. Principles of Standard • Existing code is important, existing implementations are not. • C code can be portable. C code can be non-portable. • Avoid “quiet changes.” • Keep the spirit of C.

  46. The Spirit of C • Trust the programmer. Don’t prevent the programmer from doing what needs to be done. • Keep the language small and simple. • Provide only one way to do an operation. • Make it fast, even if it is not guaranteed to be portable.

  47. Overview of C Standard • Eight sections: Scope, Normative references, Terms, definitions, and symbols, Conformance, Environment, Language, Library, Annex. • It specifies: the representation of C programs; the syntax and constraints of the C language; the semantic rules for interpreting C programs; etc..

  48. Some Special Terms • Undefined behavior: behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements • Implementation-defined behavior • Recommended practice

  49. Access: (execution-time action) to read or modify the value of an object. • Bit: unit of data storage in the execution environment large enough to hold an object that may have one of two values • Alignment • Argument/parameter

  50. Language Lawyer • A language lawyer is distinguished by the ability to show you the five sentences scattered through a 200-page manual that together imply the answer to your question "if only you had thought to look there".

More Related