C++ sizeof 使用規則及陷阱分析

From: http://freeman.cnblogs.com/articles/sizeof.html 前言 50米的網站http://www.50mi.net開張了,所以50米邀請我給他寫點什麼。說實在的,作爲一個資深的潛水員,我還真沒動筆寫過什麼東西,所以絞盡腦汁也沒想起來能寫什麼的。不過鑑於50米喜歡在小孩子面前臭屁的,就寫一篇羣裏討論很多的sizeof問題吧。 1、什麼是sizeof 首先看一下sizeof在msdn上的定義: The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t. 看到return這個字眼,是不是想到了函數?錯了,sizeof不是一個函數,你見過給一個函數傳參數,而不加括號的嗎?sizeof可以,所以 sizeof不是函數。網上有人說sizeof是一元操作符,但是我並不這麼認爲,因爲sizeof更像一個特殊的宏,它是在編譯階段求值的。舉個例子: cout< using namespace std; int Sum(int i[]) { int sumofi = 0; for (int j = 0; j < sizeof(i)/sizeof(int); j++) //實際上,sizeof(i) = 4 { sumofi += i[j]; } return sumofi; } int main() { int allAges[6] = {21, 22, 22, 19, 34, 12}; cout< using namespace std; int Sum(int *i, unsigned int n) { int sumofi = 0; for (int j = 0; j < n; j++) { sumofi += i[j]; } return sumofi; } int main() { int allAges[] = {21, 22, 22, 19, 34, 12}; cout<
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章