2012-09-18 36 views
2

我只是經歷了一些C代碼,當我陷入這段代碼。一個變量的硬編碼,令人困惑的C語法

void someFunction(Int32 someVariable) 
{ 
    /* someVariable is hard coded to 2 */ 
    (void)someVariable; 

    //some processing that has nothing to do with someVariable. 
} 

什麼是由註釋,意味着作者 「someVariable是硬編碼到2」? 究竟發生了什麼someVariable

+0

作者可能試圖優化這個函數。他們碰巧知道someVariable總是2,所以他們編寫函數來使用該文字值而不是變量。 –

+0

它使'someVariable'等於'2'?沒有涉及常量? @VaughnCato –

+0

我猜someFunction總是被調用的值爲2. –

回答

2

這意味着使用的代碼看起來像這樣,例如:

// Somewhere else in the source: 
…someFunction(2)… 
… 
…x = 2;… 
…someFunction(x)… 
… 
// Et cetera, the point being that whenever someFunction is called, its argument always has the value 2. 

// The definition of someFunction: 
void someFunction(Int32 someVariable) 
{ 
    foo(someVariable*3); 
    y = someVariable*7 - 4; 
    bar(y); 
    … 
} 

和作者把它改成這樣:

// The definition of someFunction: 
void someFunction(Int32 someVariable) 
{ 
    (void) someVariable; 
    foo(6); 
    y = 10; 
    bar(y); 
    … 
} 

那麼,什麼情況是:

  • 「someVariable」出現在「someFunction」中的任何地方,作者用「2」代替它。
  • 作者然後減少表達式,以便「someVariable * 3」變成「2 * 3」,然後變成「6」。這就解釋了爲什麼你在某些函數中看不到「someVariable」,爲什麼你在某些函數中看不到「2」。

換句話說,someFunction的代碼現在的行爲的原代碼的表現時someVariable是2.您描述someFunction的身體「有沒有關係someVariable一些處理」的方式,但事實上,它是爲someVariable的變量使用2的處理。無論角色someVariable在函數中扮演的角色是否已經被編輯所遺失,但是,大概這種代碼的行爲就像舊代碼一樣,只要someVariable是2.

+0

感謝這麼好的解釋。 :) –

4

聲明

(void)someVariable; 

將禁止任何編譯器警告該參數someVariable是函數內的使用。

如果你看看後面的代碼,你可能會發現它可以使用someVariable的值的地方,但是代之以硬編碼,假設它是2

+0

我經歷了其餘的代碼,但它並沒有通過'(void)someVariable' LOC使用'someVariable'。這是否意味着'someVariable'已被設置爲'2',意思是'someVariable = 2'? –

+0

@SeanVaughn *假設* someVariable'是'2'。 – ecatmur

+0

爲什麼正好2?沒有提及常量。 –

6

大多數情況下(將函數參數轉換爲void)是爲了關閉編譯器,否則會由於未使用的參數而發出警告或出錯。在某個地方值是「硬編碼」與提供的代碼無關。