我正在使用宏來為我的代碼中的某些陣列定義靜態大小,我在我的代碼頂部定義了一個配置宏變數,并且一些宏變數取決于所述宏變數。我可以創建一個函式來獲取該值并回傳所需的陣列大小,但這將在運行時執行,我需要使用 VLA。下面的示例顯示了數字大小(沒有重復數字)的宏以及該數字是否可以以零開頭(“0123”與“1234”)。
在運行時計算 LIMIT 的代碼:
int limit(int size, int npz){
l = npz ? 9 : 10;
for(int i = 1; i < size; i )
l *= 10 - i;
return l;
}
我手動計算了所有值的所述數字的數量。有解決辦法嗎?
#define SIZE 4 // 1 .. 10
#define NO_PADDING_ZERO 1 // 1 | 0
#if NO_PADDING_ZERO
#if SIZE == 1
#define LIMIT 9
#elif SIZE == 2
#define LIMIT 81
#elif SIZE == 3
#define LIMIT 648
#elif SIZE == 4
#define LIMIT 4536
#elif SIZE == 5
#define LIMIT 27216
#elif SIZE == 6
#define LIMIT 136080
#elif SIZE == 7
#define LIMIT 544320
#elif SIZE == 8
#define LIMIT 1632960
#else
#define LIMIT 3265920
#endif
#else
#if SIZE == 1
#define LIMIT 10
#elif SIZE == 2
#define LIMIT 90
#elif SIZE == 3
#define LIMIT 720
#elif SIZE == 4
#define LIMIT 5040
#elif SIZE == 5
#define LIMIT 30240
#elif SIZE == 6
#define LIMIT 151200
#elif SIZE == 7
#define LIMIT 604800
#elif SIZE == 8
#define LIMIT 1814400
#else
#define LIMIT 3628800
#endif
#endif
uj5u.com熱心網友回復:
解決方法可能是從其他東西生成C 代碼。
考慮學習更多,使用GPP或您自己的 C 代碼生成器(可能使用GNU bison,在某些簡單的情況下使用GNU gawk或GNU autoconf)。
請注意,在 Linux 或 POSIX 上,您可以生成 C 代碼,將其編譯為插件,然后dlopen(3)該插件。有關無用的示例,請參閱manydl.c。有關有用(但已過時)的示例,請參閱我的舊GCC MELT。
另一種方法(特定于GCC)可能是使用GCC 插件擴展您的編譯器。見比斯蒙。
您還可以使用GNU Lightning或(在 C 中)asmjit生成機器代碼(在您的程式中) 。然后閱讀龍書和這個答案。
閱讀Jacques Pitrat的一些書籍,解釋元編程方法(在RefPerSys中重用)
與部分評估相關的概念是相關的。
uj5u.com熱心網友回復:
這是某種階乘嗎?
(10 - NO_PADDING_ZERO) * 9 * 8 * ... * (10 - LIMIT)
您可以在宏或行內函式的回圈運算式中使用它,優化編譯器將在編譯時計算它。
#include <bool.h>
inline int limit(int size, bool npz){
int l = 10 - npz;
for(int i = 1; i < size; i )
l *= 10 - i;
return l;
}
#define LIMIT (limit(SIZE, NO_PADDING_ZERO))
如果您愿意,您可以定義一個預先計算的陣列并使用
#define LIMIT (array[SIZE][NO_PADDING_ZERO])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487165.html
