[英]int* const* foo(int x); is a valid C function prototype. How do you “read” this return type?
在閱讀Jeff Lee於1985年發布的ANSI C語法規范時,我注意到這是一個有效的原型,並且我使用此簽名編譯了一個函數。 帶有此原型的函數究竟會返回什么? 這個函數的簡單主體是什么樣子?
返回類型是指向int的const指針。 從右到左閱讀聲明,它將使事情變得容易得多。 我最喜歡的復雜指針聲明教程: http : //c-faq.com/decl/spiral.anderson.html
一些(相當人為的)示例:
#include <iostream>
int* const * foo(int x)
{
static int* const p = new int[x]; // const pointer to array of x ints
for(int i = 0; i < x ; ++i) // initialize it with some values
p[i] = i;
return &p; // return its address
}
int main()
{
int* const* p = foo(10); // our pointer to const pointer to int
//*p = nullptr; // illegal, cannot modify the dereferenced pointer (const)
std::cout << (*p)[8]; // display the 8-th element
}
foo
是一個函數,它的int
參數,並返回一個指向const
指向一個int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.