赛派号

定型喷雾什么牌子比较好用 C (programming language)

"C programming language" redirects here. For the book, see The C Programming Language. Not to be confused with C++ or C#.

C[c] is a general-purpose programming language. It was created in the 1970s by Dennis Ritchie and remains widely used and influential. By design, C gives the programmer relatively direct access to the features of the typical CPU architecture, customized for the target instruction set. It has been and continues to be used to implement operating systems (especially kernels[10]), device drivers, and protocol stacks, but its use in application software has been decreasing.[11] C is used on computers that range from the largest supercomputers to the smallest microcontrollers and embedded systems.

CLogotype used on the cover of the first edition of The C Programming Language[1]ParadigmMulti-paradigm: imperative (procedural), structuredDesigned byDennis RitchieDeveloperANSI X3J11 (ANSI C); ISO/IEC JTC 1 (Joint Technical Committee 1) / SC 22 (Subcommittee 22) / WG 14 (Working Group 14) (ISO C)First appeared1972; 53 years ago (1972)[a]Stable releaseC23 / October 31, 2024; 10 months ago (2024-10-31)Preview releaseC2y (N3220) / February 21, 2024; 19 months ago (2024-02-21)[5] Typing disciplineStatic, weak, manifest, nominalOSCross-platformFilename extensions.c, .hWebsitec-language.orgiso.orgopen-std.orgMajor implementationspcc, GCC, Clang, Intel C, C++Builder, Microsoft Visual C++, Watcom CDialectsCyclone, Unified Parallel C, Split-C, Cilk, C*Influenced byB (BCPL, CPL), ALGOL 68,[b] PL/I, FortranInfluencedNumerous: AMPL, AWK, csh, C++, C--, C#, Objective-C, D, Go, Ja, JaScript, JS++, Julia, Limbo, LPC, Perl, PHP, Pike, Processing, Python, Rust, Seed7, V (Vlang), Vala, Verilog (HDL),[8] Nim, Zig C Programming at Wikibooks

A successor to the programming language B, C was originally developed at Bell Labs by Ritchie between 1972 and 1973 to construct utilities running on Unix. It was applied to re-implementing the kernel of the Unix operating system.[12] During the 1980s, C gradually gained popularity. It has become one of the most widely used programming languages,[13][14] with C compilers ailable for practically all modern computer architectures and operating systems. The book The C Programming Language, co-authored by the original language designer, served for many years as the de facto standard for the language.[15][1] C has been standardized since 1989 by the American National Standards Institute (ANSI) and, subsequently, jointly by the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC).

C is an imperative procedural language, supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support. Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant C program written with portability in mind can be compiled for a wide variety of computer platforms and operating systems with few changes to its source code.

Although neither C nor its standard library provide some popular features found in other languages, it is flexible enough to support them. For example, object orientation and garbage collection are provided by external libraries GLib Object System and Boehm garbage collector, respectively.

Since 2000, C has consistently ranked among the top four languages in the TIOBE index, a measure of the popularity of programming languages.[16]

Contents 1 Characteristics 2 "Hello, world" example 3 History 3.1 Early developments 3.1.1 B 3.1.2 New B and first C release 3.1.3 Structures and Unix kernel re-write 3.2 K&R C 3.3 ANSI C and ISO C 3.4 C99 3.5 C11 3.6 C17 3.7 C23 3.8 C2Y 3.9 Embedded C 4 Definition 4.1 Character set 4.2 Reserved words 4.3 Operators 4.4 Data types 4.4.1 Pointers 4.4.2 Arrays 4.4.3 Array–pointer interchangeability 4.5 Memory management 4.6 Libraries 4.6.1 File handling and streams 5 Language tools 6 Uses 6.1 Rationale for use in systems programming 6.2 Games 6.3 World Wide Web 6.4 C as an intermediate language 6.5 Computationally intensive libraries 6.6 Other languages are written in C 7 Limitations 8 Related languages 9 See also 10 Notes 11 References 12 Sources 13 Further reading 14 External links Characteristics edit  Dennis Ritchie (right), the inventor of the C programming language, with Ken Thompson

The C language exhibits the following characteristics:

Free-form source code Semicolons terminate statements Curly braces group statements into blocks Executable code is contained in functions; no script-like syntax Parameters are passed by value; pass by-reference is achieved by passing a pointer to a value Relatively small number of keywords Control flow constructs, including if, for, do, while, and switch Arithmetic, bitwise, and logic operators, including +,+=,++,&,|| Multiple assignments may be performed in a single statement User-defined identifiers are not distinguished from keywords; i.e. by a sigil A variable declared inside a block is accessible only in that block and only below the declaration A function return value can be ignored A function cannot be nested inside a function, but some translators support this Run-time polymorphism may be achieved using function pointers Supports recursion Data typing is static, but weakly enforced; all variables he a type, but implicit conversion between primitive types weakens the separation of the different types User-defined data types allow for aliasing a data type specifier Syntax for array definition and access is via square bracket notation, for example month[11]. Indexing is defined in terms of pointer arithmetic. Whole arrays cannot be copied or compared without custom or library code User-defined structure types allow related data elements to be passed and copied as a unit although two structures cannot be compared without custom code to compare each field User-defined union types support overlapping members; allowing multiple data types to share the same memory location User-defined enumeration types support aliasing integer values Lacks a string type but has syntax for null-terminated strings with associated handling in its standard library Supports low-level access to computer memory via pointers Supports procedure-like construct as a function returning void Supports dynamic memory via standard library functions Includes the C preprocessor to perform macro definition, source code file inclusion, and conditional compilation Supports modularity in that files are processed separately, with visibility control via static and extern attributes Minimized functionality in the core language while relatively complex functionality such as I/O, string manipulation, and mathematical functions supported via standard library functions Resulting compiled code has relatively straightforward needs on the underlying platform, making it desirable for operating and embedded systems "Hello, world" example edit  "Hello, World!" program by Brian Kernighan (1978)

The "Hello, World!" program example that appeared in the first edition of K&R has become the model for an introductory program in most programming textbooks. The program prints "hello, world" to the standard output.

The original version was:[17]

main() { printf("hello, world\n"); }

A more modern version is:[d]

#include int main(void) { printf("hello, world\n"); }

The first line is a preprocessor directive, indicated by #include, which causes the preprocessor to replace that line of code with the text of the stdio.h header file, which contains declarations for input and output functions including printf. The angle brackets around stdio.h indicate that the header file can be located using a search strategy that selects header files provided with the compiler over files with the same name that may be found in project-specific directories.

The next code line declares the entry point function main. The run-time environment calls this function to begin program execution. The type specifier int indicates that the function returns an integer value. The void parameter list indicates that the function consumes no arguments. The run-time environment actually passes two arguments (typed int and char *[]), but this implementation ignores them. The ISO C standard (section 5.1.2.2.1) requires syntax that either is void or these two arguments – a special treatment not afforded to other functions.

The opening curly brace indicates the beginning of the code that defines the function.

The next line of code calls (diverts execution to) the C standard library function printf with the address of the first character of a null-terminated string specified as a string literal. The text \n is an escape sequence that denotes the newline character which when output in a terminal results in moving the cursor to the beginning of the next line. Even though printf returns an int value, it is silently discarded. The semicolon ; terminates the call statement.

The closing curly brace indicates the end of the main function. Prior to C99, an explicit return 0; statement was required at the end of main function, but since C99, the main function (as being the initial function call) implicitly returns 0 upon reaching its final closing curly brace.[e]

History edit Early developments edit Timeline of C language Year Informalname Officialstandard 1972 first release — 1978 K&R C — 1989,1990 ANSI C, C89,ISO C, C90 ANSI X3.159-1989ISO/IEC 9899:1990 1999 C99, C9X ISO/IEC 9899:1999 2011 C11, C1X ISO/IEC 9899:2011 2018 C17, C18 ISO/IEC 9899:2018 2024 C23, C2X ISO/IEC 9899:2024 TBA C2Y

The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language on a PDP-7 by Dennis Ritchie and Ken Thompson, incorporating several ideas from colleagues. Eventually, they decided to port the operating system to a PDP-11. The original PDP-11 version of Unix was also developed in assembly language.[12]

B edit Main article: B (programming language)

Thompson wanted a programming language for developing utilities for the new platform. He first tried writing a Fortran compiler, but he soon ge up the idea and instead created a cut-down version of the recently developed systems programming language called BCPL. The official description of BCPL was not ailable at the time,[19] and Thompson modified the syntax to be less 'wordy' and similar to a simplified ALGOL known as SMALGOL.[20] He called the result B,[12] describing it as "BCPL semantics with a lot of SMALGOL syntax".[20] Like BCPL, B had a bootstrapping compiler to facilitate porting to new machines.[20] Ultimately, few utilities were written in B because it was too slow and could not take advantage of PDP-11 features such as byte addressability.

Unlike BCPL's // comment marking comments up to the end of the line, B adopted /* comment */ as the comment delimiter, more akin to PL/1, and allowing comments to appear in the middle of lines. (BCPL's comment style would be reintroduced in C++.)[12]

New B and first C release edit

In 1971 Ritchie started to improve B, to use the features of the more-powerful PDP-11. A significant addition was a character data type. He called this New B (NB).[20] Thompson started to use NB to write the Unix kernel, and his requirements shaped the direction of the language development.[20][21]

Through to 1972, richer types were added to the NB language. NB had arrays of int and char, and to these types were added pointers, the ability to generate pointers to other types, arrays of all types, and types to be returned from functions. Arrays within expressions were effectively treated as pointers. A new compiler was written, and the language was renamed C.[12]

The C compiler and some utilities made with it were included in Version 2 Unix, which is also known as Research Unix.[22]

Structures and Unix kernel re-write edit

At Version 4 Unix, released in November 1973, the Unix kernel was extensively re-implemented in C.[12] By this time, the C language had acquired some powerful features such as struct types.

The preprocessor was introduced around 1973 at the urging of Alan Snyder and also in recognition of the usefulness of the file-inclusion mechanisms ailable in BCPL and PL/I. Its original version provided only included files and simple string replacements: #include and #define of parameterless macros. Soon after that, it was extended, mostly by Mike Lesk and then by John Reiser, to incorporate macros with arguments and conditional compilation.[12]

Unix was one of the first operating system kernels implemented in a language other than assembly. Earlier instances include the Multics system (which was written in PL/I) and Master Control Program (MCP) for the Burroughs B5000 (which was written in ALGOL) in 1961. In and around 1977, Ritchie and Stephen C. Johnson made further changes to the language to facilitate portability of the Unix operating system. Johnson's Portable C Compiler served as the basis for several implementations of C on new platforms.[21]

K&R C edit  The cover of the book The C Programming Language, first edition, by Brian Kernighan and Dennis Ritchie

In 1978 Brian Kernighan and Dennis Ritchie published the first edition of The C Programming Language.[23] Known as K&R from the initials of its authors, the book served for many years as an informal specification of the language. The version of C that it describes is commonly referred to as "K&R C". As this was released in 1978, it is now also referred to as C78.[24] The second edition of the book[25] covers the later ANSI C standard, described below.

K&R introduced several language features:

Standard I/O library long int data type unsigned int data type Compound assignment operators of the form =op (such as =-) were changed to the form op= (that is, -=) to remove the semantic ambiguity created by constructs such as i=-10, which had been interpreted as i =- 10 (decrement i by 10) instead of the possibly intended i = -10 (let i be −10).

Even after the publication of the 1989 ANSI standard, for many years K&R C was still considered the "lowest common denominator" to which C programmers restricted themselves when maximum portability was desired, since many older compilers were still in use, and because carefully written K&R C code can be legal Standard C as well.

Although later versions of C require functions to he an explicit type declaration, K&R C only requires functions that return a type other than int to be declared before use. Functions used without prior declaration were presumed to return int.

For example:

long long_function(); calling_function() { long longvar; register intvar; longvar = long_function(); if (longvar > 1) intvar = 0; else intvar = int_function(); return intvar; }

The declaration of long_function() (on line 1) is required since it returns long; not int. Function int_function can be called (line 11) even though it is not declared since it returns int. Also, variable intvar does not need to be declared as type int since that is the default type for register keyword.

Since function declarations did not include information about arguments, type checks were not performed, although some compilers would issue a warning if different calls to a function used different numbers or types of arguments. Tools such as Unix's lint utility were developed that (among other things) checked for consistency of function use across multiple source files.

In the years following the publication of K&R C, several features were added to the language, supported by compilers from AT&T (in particular PCC[26]) and other vendors. These included:

void functions; functions returning no value Functions returning struct or union types Assignment for struct variables Enumerated types

The popularity of the language, lack of agreement on standard library interfaces, and lack of compliance to the K&R specification, led to standardization efforts.[27]

ANSI C and ISO C edit Main article: ANSI C

During the late 1970s and 1980s, versions of C were implemented for a wide variety of mainframe computers, minicomputers, and microcomputers, including the IBM PC, as its popularity increased significantly.

In 1983 the American National Standards Institute (ANSI) formed a committee, X3J11, to establish a standard specification of C. X3J11 based the C standard on the Unix implementation; however, the non-portable portion of the Unix C library was handed off to the IEEE working group 1003 to become the basis for the 1988 POSIX standard. In 1989, the C standard was ratified as ANSI X3.159-1989 "Programming Language C". This version of the language is often referred to as ANSI C, Standard C, or sometimes C89.

In 1990 the ANSI C standard (with formatting changes) was adopted by the International Organization for Standardization (ISO) as ISO/IEC 9899:1990, which is sometimes called C90. Therefore, the terms "C89" and "C90" refer to the same programming language.

ANSI, like other national standards bodies, no longer develops the C standard independently, but defers to the international C standard, maintained by the working group ISO/IEC JTC1/SC22/WG14. National adoption of an update to the international standard typically occurs within a year of ISO publication.

One of the aims of the C standardization process was to produce a superset of K&R C, incorporating many of the subsequently introduced unofficial features. The standards committee also included several additional features such as function prototypes (borrowed from C++), void pointers, support for international character sets and locales, and preprocessor enhancements. Although the syntax for parameter declarations was augmented to include the style used in C++, the K&R interface continued to be permitted, for compatibility with existing source code.

C89 is supported by current C compilers, and most modern C code is based on it. Any program written only in Standard C and without any hardware-dependent assumptions will run correctly on any platform with a conforming C implementation, within its resource limits. Without such precautions, programs may compile only on a certain platform or with a particular compiler, due, for example, to the use of non-standard libraries, such as GUI libraries, or to a reliance on compiler- or platform-specific attributes such as the exact size of data types and byte endianness.

In cases where code must be compilable by either standard-conforming or K&R C-based compilers, the __STDC__ macro can be used to split the code into Standard and K&R sections to prevent the use on a K&R C-based compiler of features ailable only in Standard C.

After the ANSI/ISO standardization process, the C language specification remained relatively static for several years. In 1995, Normative Amendment 1 to the 1990 C standard (ISO/IEC 9899/AMD1:1995, known informally as C95) was published, to correct some details and to add more extensive support for international character sets.[28]

C99 edit Main article: C99

The C standard was further revised in the late 1990s, leading to the publication of ISO/IEC 9899:1999 in 1999, which is commonly referred to as "C99". It has since been amended three times by Technical Corrigenda.[29]

C99 introduced several new features, including inline functions, several new data types (including long long int and a complex type to represent complex numbers), variable-length arrays and flexible array members, improved support for IEEE 754 floating point, support for variadic macros (macros of variable arity), and support for one-line comments beginning with //, as in BCPL or C++. Many of these had already been implemented as extensions in several C compilers.

C99 is for the most part backward compatible with C90, but is stricter in some ways; in particular, a declaration that lacks a type specifier no longer has int implicitly assumed. A standard macro __STDC_VERSION__ is defined with value 199901L to indicate that C99 support is ailable. GCC, Solaris Studio, and other C compilers now[when?] support many or all of the new features of C99. The C compiler in Microsoft Visual C++, however, implements the C89 standard and those parts of C99 that are required for compatibility with C++11.[30][needs update]

In addition, the C99 standard requires support for identifiers using Unicode in the form of escaped characters (e.g. \u0040 or \U0001f431) and suggests support for raw Unicode names.

C11 edit Main article: C11 (C standard revision)

Work began in 2007 on another revision of the C standard, informally called "C1X" until its official publication of ISO/IEC 9899:2011 on December 8, 2011. The C standards committee adopted guidelines to limit the adoption of new features that had not been tested by existing implementations.

The C11 standard adds numerous new features to C and the library, including type generic macros, anonymous structures, improved Unicode support, atomic operations, multi-threading, and bounds-checked functions. It also makes some portions of the existing C99 library optional, and improves compatibility with C++. The standard macro __STDC_VERSION__ is defined as 201112L to indicate that C11 support is ailable.

C17 edit Main article: C17 (C standard revision)

C17 is an informal name for ISO/IEC 9899:2018, a standard for the C programming language published in June 2018. It introduces no new language features, only technical corrections, and clarifications to defects in C11. The standard macro __STDC_VERSION__ is defined as 201710L to indicate that C17 support is ailable.

C23 edit Main article: C23 (C standard revision)

C23 is an informal name for the current major C language standard revision and was known as "C2X" through most of its development. It builds on past releases, introducing features like new keywords, types including nullptr_t and _BitInt(N), and expansions to the standard library.[31]

C23 was published in October 2024 as ISO/IEC 9899:2024.[32] The standard macro __STDC_VERSION__ is defined as 202311L to indicate that C23 support is ailable.

C2Y edit

C2Y is an informal name for the next major C language standard revision, after C23 (C2X), that is hoped to be released later in the 2020s, hence the '2' in "C2Y". An early working draft of C2Y was released in February 2024 as N3220 by the working group ISO/IEC JTC1/SC22/WG14.[33]

Embedded C edit Main article: Embedded C

Historically, embedded C programming requires non-standard extensions to the C language to support exotic features such as fixed-point arithmetic, multiple distinct memory banks, and basic I/O operations.

In 2008, the C Standards Committee published a technical report extending the C language[34] to address these issues by providing a common standard for all implementations to adhere to. It includes a number of features not ailable in normal C, such as fixed-point arithmetic, named address spaces, and basic I/O hardware addressing.

Definition edit Main article: C syntax

C has a formal grammar specified by the C standard.[35] Line endings are generally not significant in C; however, line boundaries do he significance during the preprocessing phase. Comments may appear either between the delimiters /* and */, or (since C99) following // until the end of the line. Comments delimited by /* and */ do not nest, and these sequences of characters are not interpreted as comment delimiters if they appear inside string or character literals.[36]

C source files contain declarations and function definitions. Function definitions, in turn, contain declarations and statements. Declarations either define new types using keywords such as struct, union, and enum, or assign types to and perhaps reserve storage for new variables, usually by writing the type followed by the variable name. Keywords such as char and int specify built-in types. Sections of code are enclosed in braces ({ and }, sometimes called "curly brackets") to limit the scope of declarations and to act as a single statement for control structures.

As an imperative language, C uses statements to specify actions. The most common statement is an expression statement, consisting of an expression to be evaluated, followed by a semicolon; as a side effect of the evaluation, functions may be called and variables assigned new values. To modify the normal sequential execution of statements, C provides several control-flow statements identified by reserved keywords. Structured programming is supported by if ... [else] conditional execution and by do ... while, while, and for iterative execution (looping). The for statement has separate initialization, testing, and reinitialization expressions, any or all of which can be omitted. break and continue can be used within the loop. Break is used to lee the innermost enclosing loop statement and continue is used to skip to its reinitialisation. There is also a non-structured goto statement, which branches directly to the designated label within the function. switch selects a case to be executed based on the value of an integer expression. Different from many other languages, control-flow will fall through to the next case unless terminated by a break.

Expressions can use a variety of built-in operators and may contain function calls. The order in which arguments to functions and operands to most operators are evaluated is unspecified. The evaluations may even be interleed. However, all side effects (including storage to variables) will occur before the next "sequence point"; sequence points include the end of each expression statement, and the entry to and return from each function call. Sequence points also occur during evaluation of expressions containing certain operators (&&, ||, ?: and the comma operator). This permits a high degree of object code optimization by the compiler, but requires C programmers to take more care to obtain reliable results than is needed for other programming languages.

Kernighan and Ritchie say in the Introduction of The C Programming Language: "C, like any other language, has its blemishes. Some of the operators he the wrong precedence; some parts of the syntax could be better."[37] The C standard did not attempt to correct many of these blemishes, because of the impact of such changes on already existing software.

Character set edit

The basic C source character set includes the following characters:[38]

Lowercase and uppercase letters of the ISO basic Latin alphabet: a–z, A–Z Decimal digits: 0–9 Graphic characters: ! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~ Whitespace characters: space, horizontal tab, vertical tab, form feed, newline

The newline character indicates the end of a text line; it need not correspond to an actual single character, although for convenience C treats it as such.

The POSIX standard mandates a portable character set which adds a few characters (notably "@") to the basic C source character set. Both standards do not prescribe any particular value encoding -- ASCII and EBCDIC both comply with these standards, since they include at least those basic characters, even though they use different encoded values for those characters.

Additional multi-byte encoded characters may be used in string literals, but they are not entirely portable. Since C99 multi-national Unicode characters can be embedded portably within C source text by using \uXXXX or \UXXXXXXXX encoding (where X denotes a hexadecimal character).

The basic C execution character set contains the same characters, along with representations for the null character, alert, backspace, and carriage return.[38]

Run-time support for extended character sets has increased with each revision of the C standard.

Reserved words edit

All versions of C he reserved words that are case sensitive. As reserved words, they cannot be used for variable names.

C89 has 32 reserved words:

auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

C99 added five more reserved words: (‡ indicates an alternative spelling alias for a C23 keyword)

inline restrict _Bool ‡ _Complex _Imaginary

C11 added seven more reserved words:[39] (‡ indicates an alternative spelling alias for a C23 keyword)

_Alignas ‡ _Alignof ‡ _Atomic _Generic _Noreturn _Static_assert ‡ _Thread_local ‡

C23 reserved fifteen more words:

alignas alignof bool constexpr false nullptr static_assert thread_local true typeof typeof_unqual _BitInt _Decimal32 _Decimal64 _Decimal128

Most of the recently reserved words begin with an underscore followed by a capital letter, because identifiers of that form were previously reserved by the C standard for use only by implementations. Since existing program source code should not he been using these identifiers, it would not be affected when C implementations started supporting these extensions to the programming language. Some standard headers do define more convenient synonyms for underscored identifiers. Some of those words were added as keywords with their conventional spelling in C23 and the corresponding macros were removed.

Prior to C89, entry was reserved as a keyword. In the second edition of their book The C Programming Language, which describes what became known as C89, Kernighan and Ritchie wrote, "The ... [keyword] entry, formerly reserved but never used, is no longer reserved." and "The stillborn entry keyword is withdrawn."[40]

Operators edit Main article: Operators in C and C++

C supports a rich set of operators, which are symbols used within an expression to specify the manipulations to be performed while evaluating that expression. C has operators for:

arithmetic: +, -, *, /, % assignment: = augmented assignment: +=, -=, *=, /=, %=, &=, |=, ^=, = bitwise logic: ~, &, |, ^ bitwise shifts: Boolean logic: !, &&, || conditional evaluation: ? : equality testing: ==, != calling functions: ( ) increment and decrement: ++, -- member selection: ., -> object size: sizeof type: typeof, typeof_unqual since C23 order relations: = reference and dereference: &, *, [ ] sequencing: , subexpression grouping: ( ) type conversion: (typename)

C uses the operator = (used in mathematics to express equality) to indicate assignment, following the precedent of Fortran and PL/I, but unlike ALGOL and its derivatives. C uses the operator == to test for equality. The similarity between the operators for assignment and equality may result in the accidental use of one in place of the other, and in many cases the mistake does not produce an error message (although some compilers produce warnings). For example, the conditional expression if (a == b + 1) might mistakenly be written as if (a = b + 1), which will be evaluated as true unless the value of a is 0 after the assignment.[41]

The C operator precedence is not always intuitive. For example, the operator == binds more tightly than (is executed prior to) the operators & (bitwise AND) and | (bitwise OR) in expressions such as x & 1 == 0, which must be written as (x & 1) == 0 if that is the coder's intent.[42]

Data types edit Main article: C data types This section needs additional citations for verification. Please help improve this article by adding citations to reliable sources in this section. Unsourced material may be challenged and removed. (October 2012) (Learn how and when to remove this message)  

The type system in C is static and weakly typed, which makes it similar to the type system of ALGOL descendants such as Pascal.[43] There are built-in types for integers of various sizes, both signed and unsigned, floating-point numbers, and enumerated types (enum). Integer type char is often used for single-byte characters. C99 added a Boolean data type. There are also derived types including arrays, pointers, records (struct), and unions (union).

C is often used in low-level systems programming where escapes from the type system may be necessary. The compiler attempts to ensure type correctness of most expressions, but the programmer can override the checks in various ways, either by using a type cast to explicitly convert a value from one type to another, or by using pointers or unions to reinterpret the underlying bits of a data object in some other way.

Some find C's declaration syntax unintuitive, particularly for function pointers. (Ritchie's idea was to declare identifiers in contexts resembling their use: "declaration reflects use".)[44]

C's usual arithmetic conversions allow for efficient code to be generated, but can sometimes produce unexpected results. For example, a comparison of signed and unsigned integers of equal width requires a conversion of the signed value to unsigned. This can generate unexpected results if the signed value is negative.

Pointers edit

C supports the use of pointers, a type of reference that records the address or location of an object or function in memory. Pointers can be dereferenced to access data stored at the address pointed to, or to invoke a pointed-to function. Pointers can be manipulated using assignment or pointer arithmetic. The run-time representation of a pointer value is typically a raw memory address (perhaps augmented by an offset-within-word field), but since a pointer's type includes the type of the thing pointed to, expressions including pointers can be type-checked at compile time. Pointer arithmetic is automatically scaled by the size of the pointed-to data type.

Pointers are used for many purposes in C. Text strings are commonly manipulated using pointers into arrays of characters. Dynamic memory allocation is performed using pointers; the result of a malloc is usually cast to the data type of the data to be stored. Many data types, such as trees, are commonly implemented as dynamically allocated struct objects linked together using pointers. Pointers to other pointers are often used in multi-dimensional arrays and arrays of struct objects. Pointers to functions (function pointers) are useful for passing functions as arguments to higher-order functions (such as qsort or bsearch), in dispatch tables, or as callbacks to event handlers.[18]

A null pointer value explicitly points to no valid location. Dereferencing a null pointer value is undefined, often resulting in a segmentation fault. Null pointer values are useful for indicating special cases such as no "next" pointer in the final node of a linked list, or as an error indication from functions returning pointers. In appropriate contexts in source code, such as for assigning to a pointer variable, a null pointer constant can be written as 0, with or without explicit casting to a pointer type, as the NULL macro defined by several standard headers or, since C23 with the constant nullptr. In conditional contexts, null pointer values evaluate to false, while all other pointer values evaluate to true.

Void pointers (void *) point to objects of unspecified type, and can therefore be used as "generic" data pointers. Since the size and type of the pointed-to object is not known, void pointers cannot be dereferenced, nor is pointer arithmetic on them allowed, although they can easily be (and in many contexts implicitly are) converted to and from any other object pointer type.[18]

Careless use of pointers is potentially dangerous. Because they are typically unchecked, a pointer variable can be made to point to any arbitrary location, which can cause undesirable effects. Although properly used pointers point to safe places, they can be made to point to unsafe places by using invalid pointer arithmetic; the objects they point to may continue to be used after deallocation (dangling pointers); they may be used without hing been initialized (wild pointers); or they may be directly assigned an unsafe value using a cast, union, or through another corrupt pointer. In general, C is permissive in allowing manipulation of and conversion between pointer types, although compilers typically provide options for various levels of checking. Some other programming languages address these problems by using more restrictive reference types.

Arrays edit See also: C string handling

Array types in C are traditionally of a fixed, static size specified at compile time. The more recent C99 standard also allows a form of variable-length arrays. However, it is also possible to allocate a block of memory (of arbitrary size) at run time, using the standard library's malloc function, and treat it as an array.

Since arrays are always accessed (in effect) via pointers, array accesses are typically not checked against the underlying array size, although some compilers may provide bounds checking as an option.[45][46] Array bounds violations are therefore possible and can lead to various repercussions, including illegal memory accesses, corruption of data, buffer overruns, and run-time exceptions.

C does not he a special provision for declaring multi-dimensional arrays, but rather relies on recursion within the type system to declare arrays of arrays, which effectively accomplishes the same thing. The index values of the resulting "multi-dimensional array" can be thought of as increasing in row-major order. Multi-dimensional arrays are commonly used in numerical algorithms (mainly from applied linear algebra) to store matrices. The structure of the C array is well suited to this particular task. However, in early versions of C the bounds of the array must be known fixed values or else explicitly passed to any subroutine that requires them, and dynamically sized arrays of arrays cannot be accessed using double indexing. (A workaround for this was to allocate the array with an additional "row vector" of pointers to the columns.) C99 introduced "variable-length arrays" which address this issue.

The following example using modern C (C99 or later) shows allocation of a two-dimensional array on the heap and the use of multi-dimensional array indexing for accesses (which can use bounds-checking on many C compilers):

int func(int N, int M) { float (*p)[N] [M] = malloc(sizeof *p); if (p == 0) return -1; for (int i = 0; i

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了