简体   繁体   English

检查const数组是否在编译期间排序(C语言)

[英]Check if const array is sorted during compile time (C language)

In C language, how to check during compile time if a const array is sorted (in ascending order) or not. 在C语言中,如何在编译时检查const数组是否已排序(升序)。

Given an array like this: const int a[] = {4,5,6,8}; 给定这样的数组:const int a [] = {4,5,6,8};

Compilation should fail with error if the above array is not sorted. 如果上述数组未排序,则编译应失败并显示错误。

Is that even possible? 那有可能吗?

This is very difficult to do generically at compilation time, it may even be impossible with the standard tools (preprocessor, etc). 这是非常困难的,在编译时一般做的,它甚至可能是无法使用标准工具(预处理等)。

Perhaps a better solution would be to, as soon as possible after array creation, simply have code check it (which you can also disable like assert ): 也许更好的解决方案是在创建数组后尽快对代码进行检查(您也可以像assert一样禁用它):

const int a[] = { 4, 5, 6, 8 };
#ifndef NDEBUG
for (int i = 1; i < sizeof(a) / sizeof(a[0]); i++) {
    if (a[i-1] > a[i]) {
        fprintf (stderr, "%s(%d) Check your arrays\n", __FILE__, __LINE__);
        exit(1);
    }
}
#endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM