Why does C++ allow us to surround the variable name in parentheses when declaring a variable?

。_饼干妹妹 提交于 2019-11-26 10:35:00

Grouping.

As a particular example, consider that you can declare a variable of function type such as

int f(int);

Now, how would you declare a pointer to such a thing?

int *f(int);

Nope, doesn't work! This is interpreted as a function returning int*. You need to add in the parentheses to make it parse the right way:

int (*f)(int);

The same deal with arrays:

int *x[5];   // array of five int*
int (*x)[5]; // pointer to array of five int
Ethouris

There's generally allowed to use parentheses in such declarations because the declaration, from the syntactical point of view looks always like this:

<front type> <specification>;

For example, in the following declaration:

int* p[2];

The "front type" is int (not int*) and the "specification" is * p[2].

The rule is that you can use any number of parentheses as needed in the "specification" part because they are sometimes inevitable to disambiguate. For example:

int* p[2]; // array of 2 pointers to int; same as int (*p[2]);
int (*p)[2]; // pointer to an array of 2 ints

The pointer to an array is a rare case, however the same situation you have with a pointer to function:

int (*func(int)); // declares a function returning int*
int (*func)(int); // declares a pointer to function returning int

This is the direct answer to your question. If your question is about the statement like C(y), then:

  • Put parentheses around the whole expression - (C(y)) and you'll get what you wanted
  • This statement does nothing but creating a temporary object, which ceases to living after this instruction ends (I hope this is what you intended to do).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!