开发者

What are the most useful new features in C99? [closed]

开发者 https://www.devze.com 2022-12-16 06:19 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance开发者_Go百科. Closed 10 years ago.

C99 has been around for over 10 years, but support for it has been slow coming, so most developers have stuck with C89. Even today, I'm sometimes mildly surprised when I come across C99 features in C code.

Now that most major compilers support C99 (MSVC being a notable exception, and some embedded compilers also lagging behind), I feel that developers who work with C probably ought to know about what C99 features are available to them. Some of the features are just common features that were never standardized before (snprintf, for instance), or are familiar from C++ (flexible variable declaration placement, or single-line // comments), but some of the new features were first introduced in C99 and are unfamiliar to many programmers.

What do you find the most useful new features in C99?

For reference, the C99 standard (labelled as a draft, but identical to the updated standard, as far as I know), the list of new features, and the GCC C99 implementation status.

One feature per answer, please; feel free to leave multiple answers. Short code examples demonstrating new features are encouraged.


I'm so used to typing

for (int i = 0; i < n; ++i) { ... }

in C++ that it's a pain to use a non-C99 compiler where I am forced to say

int i;
for (i = 0; i < n; ++i ) { ... }


stdint.h, which defines int8_t, uint8_t, etc. No more having to make non-portable assumptions about how wide your integers are.

uint32_t truth = 0xDECAFBAD;


I think that the new initializer mechanisms are extremely important.

struct { int x, y; } a[10] = { [3] = { .y = 12, .x = 1 } };

OK - not a compelling example, but the notation is accurate. You can initialize specific elements of an array, and specific members of a structure.

Maybe a better example would be this - though I'd admit it isn't hugely compelling:

enum { Iron = 26, Aluminium = 13, Beryllium = 4, ... };

const char *element_names[] =
{
    [Iron]      = "Iron",
    [Aluminium] = "Aluminium",
    [Beryllium] = "Beryllium",
    ...
};


Support for one-line comments beginning with //.


Variable length arrays:

int x;
scanf("%d", &x);
int a[x];
for (int i = 0; i < x; ++i)
    a[i] = i * i;
for (int i = 0; i < x; ++i)
    printf("%d\n", a[i]);


Being able to declare variables at locations other than the start of a block.


Variadic macros. Makes it easier to generate boilerplate code with unlimited number of arguments.


snprintf() - seriously, it's worth a lot to be able to do safe formatted strings.


Flexible array members.

6.7.2.1 Structure and union specifiers

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. With two exceptions, the flexible array member is ignored. First, the size of the structure shall be equal to the offset of the last element of an otherwise identical structure that replaces the flexible array member with an array of unspecified length) Second, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

Example:

typedef struct {
  int len;
  char buf[];
} buffer;

int bufsize = 100;
buffer *b = malloc(sizeof(buffer) + sizeof(int[bufsize]));


Compound literals. Setting structures member-by-member is so '89 ;)

You can also use them to get pointers to objects with automatic storage duration without declaring unnecessary variables, eg

foo(&(int){ 4 });

insteand of

int tmp = 4;
foo(&tmp);


The bool type.

You can now do something like that:

bool v = 5;

printf("v=%u\n", v);

will print

v=1


Support for inline functions.


Compound literals, already mentioned but here's my compelling example:

struct A *a = malloc(sizeof(*a));
*a = (struct A){0};  /* full zero-initialization   */
/* or */
*a = (struct A){.bufsiz=1024, .fd=2};   /* rest are zero-initialized.  */

It's a clear way to initialize data even if it's on the heap. There is no way to forget to zero-initialize something.


The restrict keyword. Especially when you crunch numbers...


Unicode escape sequence support:

printf("It's all \u03B5\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC to me.\n");

Or even, literal Unicode characters:

printf("日本語\n");

(note: may not work depending on your locale; portable support for different encodings will take more work than this)


Hexadecimal floating point constants (0x1.8p0f) and conversion specifiers (%a, %A). If you deal with low-level numerical details frequently, these are an enormous improvement over decimal literals and conversions.

They save you from worries about rounding when specifying constants for an algorithm, and are immensely useful for debugging low-level floating-point code.


Personally, I like the acknowledgment of IEC 60559:1989 (Binary floating-point arithmetic for microprocessor systems) and much better floating-point support.

In a similar vein, setting and querying the floating-point rounding mode, checking for Nan/Infinity/subnormal numbers, etc., is great to have.

0

精彩评论

暂无评论...
验证码 换一张
取 消