1.4 C语言标准及版本
C11标准新增特性简介
重要程度:6 分
<div>
<h2>C11标准新增特性简介</h2>
<p><strong>1. 多线程支持:</strong></p>
<p>C11引入了多线程支持,通过<code>_Thread_local</code>存储类来定义线程局部存储(TLS)变量。</p>
<pre>
<code>
_Thread_local int thread_id;
void setup_thread() {
thread_id = 1; // 每个线程都有自己的thread_id
}
</code>
</pre>
<p><strong>2. 对齐控制:</strong></p>
<p>C11提供了新的对齐控制机制,如<code>_Alignas</code>关键字,用于指定数据类型的对齐方式。</p>
<pre>
<code>
struct alignas(32) MyStruct {
int x;
double y;
};
</code>
</pre>
<p><strong>3. 字符串转换宏:</strong></p>
<p>C11引入了字符串转换宏,如<code>STDC_VERSION</code>,用于表示当前标准的版本号。</p>
<pre>
<code>
#if __STDC_VERSION__ >= 201112L
printf("C11 Standard Supported\n");
#endif
</code>
</pre>
<p><strong>4. 类型别名:</strong></p>
<p>C11引入了类型别名,使用<code>_Alignof</code>关键字获取类型的对齐要求。</p>
<pre>
<code>
#include <stdalign.h>
int main() {
printf("%zu\n", _Alignof(double));
return 0;
}
</code>
</pre>
<p><strong>5. 静态断言:</strong></p>
<p>C11引入了静态断言,使用<code>_Static_assert</code>来在编译时进行断言检查。</p>
<pre>
<code>
#define MAX_ELEMENTS 100
_Static_assert(MAX_ELEMENTS <= 100, "MAX_ELEMENTS must be less than or equal to 100");
</code>
</pre>
</div>