问题:
thd_create_mutex.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
const int MAX_THREAD_NUMBER = 2;
int number = 0;
pthread_t pid[MAX_THREAD_NUMBER] = {0};
...
gcc -c -o obj/thd_create_mutex.o thd_create_mutex.c -Iinclude
thd_create_mutex.c:7: error: variably modified ‘pid’ at file scope
make: *** [obj/thd_create_mutex.o] Error 1
在C语言中,const不是一个真真正正的常量,其代表的含义仅仅是只读。使用const声明的对象是一个运行时对象,无法使用其作为某个量的初值、数组的长度、case的值或在类型的情形中使用。
如果要在C中定义编译时常量,也就是一个真正的常量,可以使用#define宏定义,但是#define的问题在于它是直接替换源代码中的所有匹配字符串,容易造成误替换,因此对于像int型这样的情况可以耍点小把戏,就像这样:
enum {MAX_THREAD_NUMBER = 256}; // Or: #define MAX_THREAD_NUMBER 256
int pid[MAX_THREAD_NUMBER];
那么我们经常说const也并非不可修改,利用某些小技巧可以绕过只读约束,下面的例子中被const限定的t就仍然可被修改:
const int a = 1;
*(int*)&a = 0;
printf("%d",a); // Output: 0