C

一,概要

C(C语言)是于1972年由Dennis Ritchie(丹尼斯.里奇,UNIX的研制者)在贝尔电话实验室里为用于Unix而发明的一种通用的程序式的程序语言。虽然C是为了实施性系统软件而设计的,但也广泛用于开发可移植性软件。具有高效、灵活、功能丰富、表达力强和较高的移植性等特点,在程序员中备受青睐。

C是最流行的编程语言之一,广泛应用于各种软件平台,几乎各个计算机架构都有一个C编译器。C也深深影响了其它流行语言,尤其是作为C语言扩展而出现的C++语言。

C语言是由UNIX的研制者丹尼斯•里奇(Dennis Ritchie)和肯•汤普逊(Ken Thompson)于1970年研制出的B语言的基础上发展和完善起来的。目前,C语言编译器普遍存在于各种不同的操作系统中,例如UNIX、MS-DOS、Microsoft Windows及Linux等。C语言的设计影响了许多后来的程序语言,例如C++、Java、C#|C#等。

后来于1980年代,为了避免各开发厂商用的C语言语法产生差异,由美国国家标准局(American National Standard Institution)为C语言订定了一套完整的国际标准语法,称为ANSI C,作为C语言的标准。1980年代至今的有关程序开发工具,一般都支持符合ANSI C的语法。

二,历史版本

设计哲学:

C语言是一个程序语言,设计目标是提供一种能以简易的方式编译、处理低阶内存、产生少量的机械码以及不需要任何执行环境支持便能执行的程序语言。C语言也很适合搭配汇编语言来使用。尽管C语言提供了许多低阶处理的功能,但仍然保持着良好跨平台的特性,以一个标准规格写出的C语言程序可在许多计算机平台上进行编译,甚至包含一些嵌入式处理器(微控制器或称MCU)以及超级计算机等作业平台。

1,早期发展

名称 发布时间 GCC参数 语言实现时函数库
早期C
C89(C90,ANSI C,X3.159-1989,ISO/IEC 9899:1990) 1989年标准通过,1990年发布

-ansi

-std=c90

-std=iso9899:1990

(带C扩展时)-std=gnu90

<float.h>

<limits.h>

<stdarg.h>

<stddef.h>

AMD1,C94,C95 1995年

-std=iso9899:199409

<iso646.h>

C99,ISO/IEC 9899:1999 1999年

-std=c99

-std=iso9899:1999

(带C扩展时)-std=gnu99

<stdbool.h>

<stdint.h>

C11,ISO/IEC 9899:2011 2011年

-std=c11

-std=iso9899:2011

(带C扩展时)-std=gnu11

<stdalign.h>

<stdnoreturn.h>

C语言的第一次发展在1969年到1973年之间。之所以被称为“C”是因为C语言的很多特性是由一种更早的被称为B语言的程序语言中发展而来。早期操作系统的核心大多由汇编语言组成,随着C语言的发展,C语言已经可以用来编写操作系统的核心。1973年,Unix操作系统的核心正式用C语言改写,这是C语言第一次应用在操作系统的核心编写上。

The initial development of C occurred at AT&T Bell Labs between 1969 and 1973; according to Ritchie, the most creative period occurred in 1972. It was named “C” because many of its features were derived from an earlier language called “B”, which according to Ken Thompson was a stripped-down version of the BCPL programming language.

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 Ritchie and Thompson, incorporating several ideas from colleagues. Eventually they decided to port the operating system to a PDP-11. B's lack of functionality to take advantage of some of the PDP-11's features, notably byte addressability, led to the development of an early version of the C programming language.

The original PDP-11 version of the Unix system was developed in assembly language. By 1973, with the addition of struct types, the C language had become powerful enough that most of the Unix kernel was rewritten in C. This was one of the first operating system kernels implemented in a language other than assembly. (Earlier instances include the Multics system (written in PL/I), and MCP (Master Control Program) for the Burroughs B5000 written in ALGOL in 1961.)

2,K&R C

1978年,丹尼斯•里奇(Dennis Ritchie)和Brian Kernighan合作出版了《C程序设计语言 (书)|C程序设计语言》的第一版。书中介绍的C语言标准也被C语言程序设计师称作“K&R C”,第二版的书中也包含了一些ANSI C的标准。K&R C主要介绍了以下特色: *结构(<tt>struct</tt>)类型 *长整数(<tt>long int</tt>)类型 *无号整数(<tt>unsigned int</tt>)类型 *把运算符<tt>=+</tt>和<tt>=-</tt>改为<tt>+=</tt>和<tt>-=</tt>。因为<tt>=+</tt>和<tt>=-</tt>会使得编译器不知道使用者要处理<tt>i = +10</tt>还是<tt>i =- 10</tt>,使得处理上产生混淆。

即使在后来ANSI C标准被提出的许多年后,K&R C仍然是许多编译器的最低标准要求,许多老旧的编译仍然运行K&R C的标准。

3,ANSI C 和 ISO C

1989年,C语言被 ANSI 标准化(ANSI X3.159-1989)。标准化的一个目的是扩展K&R C。这个标准包括了一些新特性。在K&R出版后,一些新特性被非官方地加到C语言中。

*<tt>void</tt> 函数 *函数返回 <tt>struct</tt> 或 <tt>union</tt> 类型 *<tt>void *</tt> 数据类型

在ANSI标准化自己的过程中,一些新的特性被加了进去。ANSI也规定一套了标准函数库。ANSI ISO(国际标准化组织)成立 ISO/IEC JTC1/SC22/WG14 工作组,来规定国际标准的C语言。通过对ANSI标准的少量修改,最终通过了 ISO 9899:1990。随后,ISO标准被 ANSI 采纳。

传统C语言到ANSI/ISO标准C语言的改进包括: *增加了真正的标准库 *新的预处理命令与特性 *函数原型允许在函数申明中指定参数类型 *一些新的关键字,包括 <tt>const</tt>、<tt>volatile</tt> 与 <tt>signed</tt> *宽字符、宽字符串与字节多字符 *对约定规则、声明和类型检查的许多小改动与澄清

WG14工作小组之后又于1995年,对1985年颁布的标准做了两处技术修订(缺陷修复)和一个补充(扩展)。下面是 1995 年做出的所有修改: *3 个新的标准库头文件 iso646.h、wctype.h 和 wchar.h *几个新的记号与预定义宏,用于对国际化提供更好的支持 *printf/sprintf 函数一系列新的格式代码 *大量的函数和一些类型与常数|常量,用于多字节字符和宽字节字符

4,C99

在ANSI的标准确立后,C语言的规范在一段时间内没有大的变动,然而C++在自己的标准化建立过程中继续发展壮大。《标准修正案一》在1995年为C语言建立了一个新标准,但是只修正了一些C89标准中的细节和增加更多更广得国际字符集支持。不过,这个标准引出了1999年ISO 9899:1999的发表。它通常被成为C99。C99被ANSI于2000年3月采用。

在C99中包括的特性有:

*对编译器限制增加了,比如源程序每行要求至少支持到 4095 字节,变量名函数名的要求支持到 63 字节(extern 要求支持到 31) *预处理增强了。例如: **宏支持取可变参数 #define Macro(...) __VA_ARGS__ **使用宏的时候,参数如果不写,宏里用 #,## 这样的东西会扩展成空串。(以前会出错的) **支持 // 行注释(这个特性实际上在C89的很多编译器上已经被支持了) *增加了新关键字 restrict, inline, _Complex, _Imaginary, _Bool **支持 long long, long double _Complex, float _Complex 这样的类型 *支持 <: :> <% %> %: %:%: ,等等奇怪的符号替代,D&E 里提过这个 *支持了不定长的数组。数组的长度就可以用变量了。声明类型的时候呢,就用 int a[*] 这样的写法。不过考虑到效率和实现,这玩意并不是一个新类型。所以就不能用在全局里,或者 struct union 里面,如果你用了这样的东西,goto 语句就受限制了。 *变量声明不必放在语句块的开头,for 语句提倡这么写 for(int i=0;i<100;++i) 就是说,int i 的声明放在里面,i 只在 for 里面有效。 *当一个类似结构的东西需要临时构造的时候,可以用(type_name){xx,xx,xx} 这有点像 C++ 的构造函数 *初始化结构的时候现在可以这样写: *:<source lang="c">struct {int a[3],b;} hehe[] = { [0].a = {1}, [1].a = 2 };</source> *:<source lang="c">struct {int a, b, c, d;} hehe = { .a = 1, .c = 3, 4, .b = 5} // 3,4 是对 .c,.d 赋值的</source> *字符串里面,\u 支持 unicode 的字符 *支持 16 进制的浮点数的描述 *所以 printf scanf 的格式化串多支持了 ll / LL(VC6 里用的 I64)对应新的 long long 类型。 *浮点数的内部数据描述支持了新标准,这个可以用 #pragma 编译器指定 *除了已经有的 __line__ __file__ 以外,又支持了一个 __func__ 可以得到当前的函数名 *对于非常数的表达式,也允许编译器做化简 *修改了对于/% 处理负数上的定义,比如老的标准里 -22 / 7 = -3, -22 % 7 = -1 而现在 -22 / 7 = -4, -22 % 7 = 6 *取消了不写函数返回类型默认就是 int 的规定 *允许 struct 定义的最后一个数组写做 [] 不指定其长度描述 *const const int i;将被当作 const int i;处理 *增加和修改了一些标准头文件,比如定义 bool 的 <stdbool.h> 定义一些标准长度的 int 的 <inttypes.h> 定义复数的 <complex.h> 定义宽字符的 <wctype.h> 有点泛型味道的数学函数 <tgmath.h> 跟浮点数有关的 <fenv.h>。<stdarg.h> 里多了一个 va_copy 可以复制 ... 的参数。<time.h> 里多了个 struct tmx 对 struct tm 做了扩展 *输入输出对宽字符还有长整数等做了相应的支持

但是各个公司对C99的支持所表现出来的兴趣不同。当GCC和其它一些商业编译器支持C99的大部分特性的时候,微软和Borland却似乎对此不感兴趣。

5,C1X

2007年开始C规范的新版本C1X的制定,C标准委员会对未经实际工程测试过的新功能限制使用。

三,用途

C虽不擅长科学计算和管理领域,但对操作系统和系统实用程序以及对硬件进行操作方面,C有明显的优势。现在很多大型应用软件也用C编写。

C's primary use is for “system programming”, including implementing operating systems and embedded system applications, due to a combination of desirable characteristics such as code portability and efficiency, ability to access specific hardware addresses, ability to “pun” types to match externally imposed data access requirements, and low runtime demand on system resources.

One consequence of C's wide acceptance and efficiency is that compilers, libraries, and interpreters of other programming languages are often implemented in C.

C is sometimes used as an intermediate language by implementations of other languages. This approach may be used for portability or convenience; by using C as an intermediate language, it is not necessary to develop machine-specific code generators. Some compilers which use C this way are BitC, Gambit, the Glasgow Haskell Compiler, Squeak, and Vala.

Unfortunately, C was designed as a programming language, not as a compiler target language, and is thus less than ideal for use as an intermediate language. This has led to development of C-based intermediate languages such as C–.

C has also been widely used to implement end-user applications, but as applications became larger, much of that development shifted to other languages.

四,特色与优点缺点

1. C语言的特点 ①语言简洁、紧凑,使用方便、灵活。只有32个关键字(保留字,reserved keywords),使变量、函数命名有更多弹性。有9种控制语句。

②运算符丰富,公有34种运算符。

③数据结构丰富,数据类型有:整型、实型、字符型、数组、指针、结构体、共用体等。

④具有结构化的控制语句(如if…else、while、do…while、switch、for)

⑤语法限制不太严格,程序设计自由度大。

⑥允许直接访问物理地址,能进行位(bit)操作,可以直接对硬件操作。

⑦生成目标代码质量高,程序执行效率高。

⑧可移植性好。

* C语言是一个有结构化程序设计、具有变量作用域(variable scope)以及递归功能的程序式语言。

* 传递参数是以值传递(Pass-by-value),也可以透过指针来传递参数(Pass-by-address)。

* 不同的变量类型可以用结构体(struct)组合在一起。

* 只有32个保留字(reserved keywords),使变量、函数命名有更多弹性。

* 部份的变量类型可以转换,例如整形和字符变量。

* 透过指针(pointer),C语言可以容易的对内存进行低阶控制。

* 编译预处理(preprocessor)让C语言的编译更具有弹性。

Like most imperative languages in the ALGOL tradition, C has facilities for structured programming and allows lexical variable scope and recursion, while a static type system prevents many unintended operations. In C, all executable code is contained within functions. Function parameters are always passed by value. Pass-by-reference is achieved in C by explicitly passing pointer values. Heterogeneous aggregate data types (struct) allow related data elements to be combined and manipulated as a unit. C program source text is free-format, using the semicolon as a statement terminator (not a delimiter).

C also exhibits the following more specific characteristics: lack of nested function definitions variables may be hidden in nested blocks partially weak typing; for instance, characters can be used as integers low-level access to computer memory by converting machine addresses to typed pointers function and data pointers supporting ad hoc run-time polymorphism array indexing as a secondary notion, defined in terms of pointer arithmetic a preprocessor for macro definition, source code file inclusion, and conditional compilation complex functionality such as I/O, string manipulation, and mathematical functions consistently delegated to library routines A relatively small set of reserved keywords A lexical structure that resembles B more than ALGOL, for example { … } rather than ALGOL's begin … end the equal-sign is for assignment (copying), much like Fortran two consecutive equal-signs are to test for equality (compare to .EQ. in Fortran or the equal-sign in BASIC) && and || in place of ALGOL's and and or (these are semantically distinct from the bit-wise operators & and | because they will never evaluate the right operand if the result can be determined from the left alone (short-circuit evaluation)). a large number of compound operators, such as +=, ++, etc.

Absent features

The relatively low-level nature of the language affords the programmer close control over what the computer does, while allowing special tailoring and aggressive optimization for a particular platform. This allows the code to run efficiently on very limited hardware, such as embedded systems.

C does not have some features that are available in some other programming languages: No direct assignment of arrays or strings (copying can be done via standard functions; assignment of objects having struct or union type is supported) No automatic garbage collection No requirement for bounds checking of arrays No operations on whole arrays No syntax for ranges, such as the A..B notation used in several languages Prior to C99, no separate Boolean type (zero/nonzero is used instead)[6] No formal closures or functions as parameters (only function and variable pointers) No generators or coroutines; intra-thread control flow consists of nested function calls, except for the use of the longjmp or setcontext library functions No exception handling; standard library functions signify error conditions with the global errno variable and/or special return values Only rudimentary support for modular programming No compile-time polymorphism in the form of function or operator overloading Only rudimentary support for generic programming Very limited support for object-oriented programming with regard to polymorphism and inheritance Limited support for encapsulation No native support for multithreading and networking No standard libraries for computer graphics and several other application programming needs

A number of these features are available as extensions in some compilers, or can be supplied by third-party libraries, or can be simulated by adopting certain coding disciplines.

Undefined behavior

Many operations in C that have undefined behavior are not required to be diagnosed at compile time. In the case of C, “undefined behavior” means that the exact behavior which arises is not specified by the standard, and exactly what will happen does not have to be documented by the C implementation. A famous, although misleading, expression in the newsgroups comp.std.c and comp.lang.c is that the program could cause “demons to fly out of your nose”.[7] Sometimes in practice what happens for an instance of undefined behavior is a bug that is hard to track down and which may corrupt the contents of memory. Sometimes a particular compiler generates reasonable and well-behaved actions that are completely different from those that would be obtained using a different C compiler. The reason some behavior has been left undefined is to allow compilers for a wide variety of instruction set architectures to generate more efficient executable code for well-defined behavior, which was deemed important for C's primary role as a systems implementation language; thus C makes it the programmer's responsibility to avoid undefined behavior, possibly using tools to find parts of a program whose behavior is undefined. Examples of undefined behavior are: accessing outside the bounds of an array overflowing a signed integer reaching the end of a non-void function without finding a return statement, when the return value is used reading the value of a variable before initializing it

These operations are all programming errors that could occur using many programming languages; C draws criticism because its standard explicitly identifies numerous cases of undefined behavior, including some where the behavior could have been made well defined, and does not specify any run-time error handling mechanism.

Invoking fflush() on a stream opened for input is an example of a different kind of undefined behavior, not necessarily a programming error but a case for which some conforming implementations may provide well-defined, useful semantics (in this example, presumably discarding input through the next new-line) as an allowed extension. Use of such nonstandard extensions generally limits software portability.

五,语法

C语言基础语法

六,内存管理

One of the most important functions of a programming language is to provide facilities for managing memory and the objects that are stored in memory. C provides three distinct ways to allocate memory for objects: Static memory allocation: space for the object is provided in the binary at compile-time; these objects have an extent (or lifetime) as long as the binary which contains them is loaded into memory Automatic memory allocation: temporary objects can be stored on the stack, and this space is automatically freed and reusable after the block in which they are declared is exited Dynamic memory allocation: blocks of memory of arbitrary size can be requested at run-time using library functions such as malloc from a region of memory called the heap; these blocks persist until subsequently freed for reuse by calling the library function free

These three approaches are appropriate in different situations and have various tradeoffs. For example, static memory allocation has no allocation overhead, automatic allocation may involve a small amount of overhead, and dynamic memory allocation can potentially have a great deal of overhead for both allocation and deallocation. On the other hand, stack space is typically much more limited and transient than either static memory or heap space, and dynamic memory allocation allows allocation of objects whose size is known only at run-time. Most C programs make extensive use of all three.

Where possible, automatic or static allocation is usually preferred because the storage is managed by the compiler, freeing the programmer of the potentially error-prone chore of manually allocating and releasing storage. However, many data structures can grow in size at runtime, and since static allocations (and automatic allocations in C89 and C90) must have a fixed size at compile-time, there are many situations in which dynamic allocation must be used. Prior to the C99 standard, variable-sized arrays were a common example of this (see malloc for an example of dynamically allocated arrays).

Automatically and dynamically allocated objects are only initialized if an initial value is explicitly specified; otherwise they initially have indeterminate values (typically, whatever bit pattern happens to be present in the storage, which might not even represent a valid value for that type). If the program attempts to access an uninitialized value, the results are undefined. Many modern compilers try to detect and warn about this problem, but both false positives and false negatives occur.

Another issue is that heap memory allocation has to be manually synchronized with its actual usage in any program in order for it to be reused as much as possible. For example, if the only pointer to a heap memory allocation goes out of scope or has its value overwritten before free() has been called, then that memory cannot be recovered for later reuse and is essentially lost to the program, a phenomenon known as a memory leak. Conversely, it is possible to release memory too soon and continue to access it; however, since the allocation system can re-allocate or itself use the freed memory, unpredictable behavior is likely to occur when the multiple users corrupt each other's data. Typically, the symptoms will appear in a portion of the program far removed from the actual error. Such issues are ameliorated in languages with automatic garbage collection or RAII.

七,类库

The C programming language uses libraries as its primary method of extension. In C, a library is a set of functions contained within a single “archive” file. Each library typically has a header file, which contains the prototypes of the functions contained within the library that may be used by a program, and declarations of special data types and macro symbols used with these functions. In order for a program to use a library, it must include the library's header file, and the library must be linked with the program, which in many cases requires compiler flags (e.g., -lm, shorthand for “math library”).

The most common C library is the C standard library, which is specified by the ISO and ANSI C standards and comes with every C implementation (“freestanding” [embedded] C implementations may provide only a subset of the standard library). This library supports stream input and output, memory allocation, mathematics, character strings, and time values.

Another common set of C library functions are those used by applications specifically targeted for Unix and Unix-like systems, especially functions which provide an interface to the kernel. These functions are detailed in various standards such as POSIX and the Single UNIX Specification.

Since many programs have been written in C, there are a wide variety of other libraries available. Libraries are often written in C because C compilers generate efficient object code; programmers then create interfaces to the library so that the routines can be used from higher-level languages like Java, Perl, and Python.

八,语言工具

Tools have been created to help C programmers avoid some of the problems inherent in the language, such as statements with undefined behavior or statements that are not a good practice because they are more likely to result in unintended behavior or run-time errors.

Automated source code checking and auditing are beneficial in any language, and for C many such tools exist, such as Lint. A common practice is to use Lint to detect questionable code when a program is first written. Once a program passes Lint, it is then compiled using the C compiler. Also, many compilers can optionally warn about syntactically valid constructs that are likely to actually be errors. MISRA C is a proprietary set of guidelines to avoid such questionable code, developed for embedded systems.

There are also compilers, libraries and operating system level mechanisms for performing array bounds checking, buffer overflow detection, serialization and automatic garbage collection, that are not a standard part of C.

Tools such as Purify, Valgrind, and linking with libraries containing special versions of the memory allocation functions can help uncover runtime memory errors.

九,相关语言

C has directly or indirectly influenced many later languages such as Java, C#, Perl, PHP, JavaScript, LPC, and Unix's C Shell. The most pervasive influence has been syntactical: all of the languages mentioned combine the statement and (more or less recognizably) expression syntax of C with type systems, data models and/or large-scale program structures that differ from those of C, sometimes radically.

When object-oriented languages became popular, C++ and Objective-C were two different extensions of C that provided object-oriented capabilities. Both languages were originally implemented as source-to-source compilers – source code was translated into C, and then compiled with a C compiler.

Bjarne Stroustrup devised the C++ programming language as one approach to providing object-oriented functionality with C-like syntax. C++ adds greater typing strength, scoping and other tools useful in object-oriented programming and permits generic programming via templates. Nearly a superset of C, C++ now supports most of C, with a few exceptions (see Compatibility of C and C++ for an exhaustive list of differences).

Unlike C++, which maintains nearly complete backwards compatibility with C, the D language makes a clean break with C while maintaining the same general syntax. It abandons a number of features of C which Walter Bright (the designer of D) considered undesirable, including the C preprocessor and trigraphs. Some, but not all, of D's extensions to C overlap with those of C++.

Objective-C was originally a very “thin” layer on top of, and remains a strict superset of, C that permits object-oriented programming using a hybrid dynamic/static typing paradigm. Objective-C derives its syntax from both C and Smalltalk: syntax that involves preprocessing, expressions, function declarations and function calls is inherited from C, while the syntax for object-oriented features was originally taken from Smalltalk.

Limbo is a language developed by the same team at Bell Labs that was responsible for C and Unix, and while retaining some of the syntax and the general style, introduced garbage collection, CSP based concurrency and other major innovations.[citation needed]

Python is a prime example of a language that has its roots deep in C. While the syntax of the language is not very similar to that of C, Python itself is written in C. This, along with the fact that Python is an open source program, allows C users to extend Python with C, or embed Python into C programs. This close relationship is one of the key factors leading to Python's success as a general-use scripting language.

Perl is another example of a popular programming language rooted in C. However, unlike Python, Perl's syntax does closely follow C syntax. Perl is also written in C and supports extensions written in C.

参见

笨办法学C语言 |

参见