2012-10-06 75 views
2

我有一個類似於下面的循環,我認爲問題是內部for循環標記爲「See here」。那有什麼問題?C++循環:';'令牌之前的預期主表達式

// measure time to write different sizes of data 
for (int i = 0; i < sizeof(sizes)/sizeof(int); i++) { 
    lengthMod = sizes[i]/sizeof(int) - 1; 

    start = wall_clock_time(); 

    for (unsigned int j = 0; j < 10; j++) // << See here!!! 
     tmp = 1; 

    // force any write back cache to flush. read from other data source 
    for (unsigned int j = 0; j < REPS; j++) // << Or here!!! 
     tmp = j; 

    end = wall_clock_time(); 
    timeTaken = ((float)(end - start))/1000000000; 
    fprintf(stderr, "%d, %1.2f \n", sizes[i]/1024, ((float)(end - start))/1000000000); 
} 

可以看到full source on GitHub〜行32


g++ -O3 cache-write.cpp -o cache-write -lrt 
cache-write.cpp: In function ‘int main()’: 
cache-write.cpp:36:27: error: expected primary-expression before ‘;’ token 
cache-write.cpp:36:27: error: expected ‘)’ before ‘;’ token 
cache-write.cpp:36:29: error: name lookup of ‘j’ changed for ISO ‘for’ scoping [-fpermissive] 
cache-write.cpp:36:29: note: (if you use ‘-fpermissive’ G++ will accept your code) 
cache-write.cpp:36:32: error: expected ‘;’ before ‘)’ token 
cache-write.cpp:44:11: error: ‘data1’ was not declared in this scope 
make: *** [cache-write] Error 1 
+4

從#define REPS行刪除尾部的';'。 – DCoder

回答

4

代替使用#define聲明REPS,使用

const unsigned int REPS = whatever; 

通常在C++中避免使用#define,因爲它可能很容易導致您遇到的問題。

+0

有沒有我應該使用'#define'的情況? 2之間有什麼區別? –

+0

@JiewMeng:'#define SYMBOL value'是一個預處理器命令。基本上預處理器將運行你的代碼,並用給定的值替換定義的「SYMBOL」的任何出現(至少在大多數情況下,儘管可能有一些更復雜的事情)。壞消息是你不能在調試器中看到一個值,所以無論你什麼時候訪問SYMBOL,都不能設置斷點,因爲你的程序中不再有'SYMBOL',它有已被替換。 'const unsigned v = value;'另一方面將由編譯器處理。 – Zeta

+0

#define由預處理器處理。預處理器執行諸如從#include文件獲取所有文本並將其放入一個長碼字符串中。 #define,因爲您使用它只是直接用我的代碼中的「REPS」替換爲「128 * MB;」。預編譯器在編譯開始之前只是操縱源代碼的文本。您通常可以將一個標誌傳遞給編譯器,這會在代碼開始編譯之前將代碼轉儲到文件中,以便您可以看到預處理器執行的操作。 –

3

您在REPS的定義的末端具有半冒號:

#define REPS 128 * MB; 
相關問題