-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathC in a Nutshell, 2nd Edition=Peter Prinz;Note=Erxin.txt
627 lines (375 loc) · 13.2 KB
/
C in a Nutshell, 2nd Edition=Peter Prinz;Note=Erxin.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
C in a Nutshell, 2nd Edition=Peter Prinz;Note=Erxin
# Preface
- code example
Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/oreillymedia/c-in-a-nutshell-2E.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
# Language
- example
// circle.c: Calculate and print the areas of circles
#include <stdio.h> // Preprocessor directive
double circularArea( double r ); // Function declaration (prototype form)
int main() // Definition of main() begins
{
double radius = 1.0, area = 0.0;
printf( " Areas of Circles\n\n" );
printf( " Radius Area\n"
"-------------------------\n" );
area = circularArea( radius );
printf( "%10.1f %10.2f\n", radius, area );
radius = 5.0;
area = circularArea( radius );
printf( "%10.1f %10.2f\n", radius, area );
return 0;
}
// The function circularArea() calculates the area of a circle
// Parameter: The radius of the circle
// Return value: The area of the circle
double circularArea( double r ) // Definition of circularArea() begins
{
const double pi = 3.1415926536; // Pi is a constant
return pi * r * r;
}
- comments
//, /**/
- character sets
The letters of the Latin alphabet
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
The decimal digits
0 1 2 3 4 5 6 7 8 9
The following 29 graphic characters
! " # % & ' () * + , − . / : ; < = > ? [ \ ] ^ _ { | } ~
The five whitespace characters
Space, horizontal tab, vertical tab, newline, and form feed
- wide characters, C has provided not only the type char but also wchar_t, the wide character type. This type, defined in the header file stddef.h
Unicode transformation formats UTF-16 and UTF-32 (see http://www.unicode.org/) for wide characters. The Unicode standard is largely identical with the ISO/IEC 10646 standard
wchar_t wx = '\x3b1'; //\x indicates a character code in hexadecimal notation to be stored in the variable
wide-character types char16_t and char32_t, which are defined as unsigned integer types
UTF-16 in C implementations that define the macro __STDC_UTF_16__
__STDC_UTF_32__, characters of the type char32_t are encoded in UTF-32
- C compiler uses the Unicode standards UTF-16 and UTF-8, then the following call to the function wctomb() (read: “wide character to multibyte”) obtains the multibyte representation of the character α
wchar_t wc = L'\x3B1'; // Greek lowercase alpha, α
char mbStr[10] = "";
int nBytes = 0;
nBytes = wctomb( mbStr, wc );
if( nBytes < 0)
puts("Not a valid multibyte character in your locale.");
c16rtomb(), which returns the multibyte character that corresponds to a given wide character of the type char16_t
- universal character names
Digraph Equivalent
<:, [
:>, ]
<%, {
%>, }
%:, #
%:%:, ##
- identifiers
a-z and A-Z
underscore character _
decimal digitis 0-9
- keywords
auto, extern, short
while, break, float
signed, _Alignas, case, for
sizeof
_Alignof
char
goto
static
_Atomic
const
if
struct
_Bool
continue
inline
switch
_Complex
default
int
typedef
_Generic
do
long
union
_Imaginary
double
register
unsigned
_Noreturn
else
restrict
void
_Static_assert
enum
return
volatile
_Thread_local
- The C compiler provides the predefined identifier __func__ for debugging
```
#include <stdio.h>
int test_func( char *s )
{
if( s == NULL) {
fprintf( stderr,
"%s: received null pointer argument\n", __func__ );
return -1;
}
/* ... */
}
```
- identifier name spaces
file scope
block scope
function prototype scope, Because these parameter names are not significant outside the prototype itself, they are meaningful only as comments
function scope, The scope of a label is always the function block in which the label occurs
+ example
struct Node { /* ... */
struct Node *next; }; // Define a structure type
void printNode( const struct Node *ptrNode); // Declare a function
int printList( const struct Node *first ) // Begin a function
{ // definition
struct Node *ptr = first;
while( ptr != NULL ) {
printNode( ptr );
ptr = ptr->next;
}
}
+ example
```
double x; // Declare a variable x with file scope
long calc( double x ); // Declare a new x with function prototype
// scope
int main()
{
long x = calc( 2.5 ); // Declare a long variable x with block scope
if( x < 0 ) // Here, x refers to the long variable
{ float x = 0.0F; // Declare a new variable x with block scope
/*...*/
}
x *= 2; // Here, x refers to the long variable again
/*...*/
}
```
# Types
- basic types
Basic types
Standard and extended integer types
Real and complex floating-point types
Enumerated types
The type void
Derived types
Pointer types
Array types
Structure types
Union types
Function types
- incomplete type
extern float fArr[ ]; // External declaration
# Literals
- integer types
signed char
int
short
long
long long
- unsigned standard integer types
_Bool
unsigned char
unsigned int
unsigned short
unsigned long
unsigned long long
- variable with type char
char ch = 'A'; // A variable with type char
printf("The character %c has the character code %d.\n", ch, ch);
for ( ; ch <= 'Z'; ++ch )
printf("%2c", ch);
- sizeof expression
sizeof(type);
sizeof expression
- compiler UTYPE_MAX etc.
unsigned int ui = UINT_MAX;
ui += 2; // Result: 1
- floating point type
float
double
long double
- 1985 standard, IEEE 754. Compilers can indicate that they support the IEC floating-point standard by defining the macro __STDC_IEC_559__
- complex floating point types, C99
The macro__STDC_NO_COMPLEX__ can be defined to indicate that the implementation does not include the header file complex.h
```
#include <complex.h>
// ...
double complex z = 1.0 + 2.0 * I;
z *= I; // Rotate z through 90° counterclockwise around the origin
```
- enumerated types
enum color { black, red, green, yellow, blue, white=7, gray };
enum color bgColor = blue, // Define two variables
fgColor = yellow; // of type enum color.
void setFgColor( enum color fgc ); // Declare a function with a
// parameter of type enum color.
- expressions of type void
(void)printf("I don't need this function's return value!\n");
void *malloc( size_t size );
void *realloc( void *ptr, size_t size );
void free( void *ptr );
+ example
```
// usingvoid.c: Demonstrates uses of the type void
// -------------------------------------------------------
#include <stdio.h>
#include <time.h>
#include <stdlib.h> // Provides the following function prototypes:
// void srand( unsigned int seed );
// int rand( void );
// void *malloc( size_t size );
// void free( void *ptr );
// void exit( int status );
enum { ARR_LEN = 100 };
int main()
{
int i, // Obtain some storage space.
*pNumbers = malloc(ARR_LEN * sizeof(int));
if ( pNumbers == NULL )
{
fprintf(stderr, "Insufficient memory.\n");
exit(1);
}
srand( (unsigned)time(NULL) ); // Initialize the
// random number generator.
for ( i=0; i < ARR_LEN; ++i )
pNumbers[i] = rand() % 10000; // Store some random numbers.
printf("\n%d random numbers between 0 and 9999:\n", ARR_LEN );
for ( i=0; i < ARR_LEN; ++i ) // Output loop:
{
printf("%6d", pNumbers[i]); // Print one number per loop
if ( i % 10 == 9 ) putchar('\n'); // iteration and a newline
} // after every 10 numbers.
free( pNumbers ); // Release the storage space.
return 0;
}
```
- the alignment of objects in memory, C11 provides the operator _Alignof to determine a type’s alignment, and the specifier _Alignas to specify the alignment in an object definition
_Alignof(int)
//alignments greater than _Alignof(max_align_t), which are known as extended alignments.
_Alignas(4) short var; // Defines var with the type short
// and four-byte alignment.
_Alignas(double) float x; // Defines x with the type float
// and the alignment of double.
//your program includes stdalign.h, you can write alignas(int) instead of _Alignas(int).
- literals
integer constants
255 is the decimal constant for the base 10 value 255
octal notation uses only the digits from 0 to 7, 047 is a valid octal constant representing 4 x 7 + 7
+ octal hexadecimal constants
int, unsigned int, long, unsigned long, long long, unsigned long long
+ example
0x200 int
512U unsigned int
0L long
0Xf0fUL unsigned long
0777LL long long
0xAAAllu unsigned long long
- floating point constants
F or f to assign a constant the type float, or the suffix L or l to give it the type long double.
- character constants
'a' 'XY' '0' '*'
- types and values of character constants
#include <stdio.h>
int c = 0;
/* ... */
c = getchar(); // Read a character.
if ( c != EOF && c > '0' && c < '6' ) // Compare input to character
// constants.
{
/* This block is executed if the user entered a digit from 1 to 5. */
}
- tyeps of character constants
none
'a'
'\t'
int
L
L'a'
L'\u0100'
wchar_t (defined in stddef.h)
u
u'a'
u'\x3b3'
char16_t (defined in uchar.h)
U
U'a'
U'\u27FA'
char32_t (defined in uchar.h)
- mbtowc() (“multibyte to wide character”), or by mbrtoc16() or mbrtoc32(), depending on the type of the wide-character constant.
- string literals
char doc_path[128] = ".\\share\\doc"; // That is, ".\share\doc"
printf("\aSee the documentation in the directory \"%s\"\n", doc_path);
- sample function error_exit()
#include <stdlib.h>
#include <stdio.h>
void error_exit(unsigned int error_n) // Print a last error message
{ // and exit the program.
char * error_msg[] = { "Unknown error code.\n",
"Insufficient memory.\n",
"Illegal memory access.\n" };
unsigned int arr_len = sizeof(error_msg)/sizeof(char *);
if ( error_n >= arr_len )
error_n = 0;
fputs( error_msg[error_n], stderr );
exit(1);
}
The prefixes u and U, introduced in C11, yield a static array of wide characters of the type char16_t or char32_t. The multibyte characters in these wide-string literals are implicitly converted to wide characters by successive calls to the function mbrtoc16() or mbrtoc32()
double angle_alpha = 90.0/3;
wprintf( L"Angle \u03b1 measures %lf degrees.\n", angle_alpha );
# Type Conversions
- conversion of arithmetic types
hierarchy of types
two signed integer types have different conversion ranks, one is wider than the other then it has a higher rank
char has the same rank as signed char and unsigned char
standard integer ranked in the order _Bool < char < short < int < long < long long
floating point ranks float < double < long double
floating point type has a higher rank than any integer type
every complex floating point type has the same rank as the type of its real and imaginary parts
- integer promotion, int is not sufficient the operand is converted to unsigned int
- example
```
#include <complex.h>
// ...
short n = -10;
double x = 0.5, y = 0.0;
float _Complex f_z = 2.0F + 3.0F * I;
double _Complex d_z = 0.0;
y = n * x; // The value of n is converted to type double.
d_z = f_z + x; // Only the value of f_z is converted to
// double _Complex.
// The result of the operation also has
// type double _Complex.
f_z = f_z / 3; // The constant value 3 is converted to float.
d_z = d_z − f_z; // The value of f_z is converted to
// the type double _Complex.
```
# Expressions and operators
# Statements
# Functions
# Arrays
# Pointers
# Structures, unions and bit-fields
# Declarations
# Dynamic memory management
# Input and output
# Multithreading
# Preprocessing directives
# Standard library
# The standard headers
# Function at a glance
# Statndard library functions
# Basic tools
# Compiling with gcc
# Using make to build C programs
# Debugging C programs with GDB
# Using an IDE with C