Consider the following code:
int main() {
int(s);
}
I am surprised by the fact that it creates valid variable s
. Can anyone explain what's happening here?
The convention in C is has generally been to declare all such local variables at the top of a function; this is different from the convention in C++ or Java, which encourage variables to be declared when they are first used.
To declare a variable as being a pointer to an array, we must make use of parentheses. This is because in C brackets ([]) have higher precedence than the asterisk (*). So if we wish to declare a pointer to an array, we need to supply parentheses to override this: double (*elephant)[20];
Variable Declaration in C You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.
Modern C compilers such as gcc and clang support the C99 and C11 standards, which allow you to declare a variable anywhere a statement could go. The variable's scope starts from the point of the declaration to the end of the block (next closing brace). You can also declare variables inside for loop initializers.
[dcl.meaning] in the Standard says:
In a declaration
T D
whereD
has the form( D1 )
the type of the contained declarator-id is the same as that of the contained declarator-id in the declarationT D1
.Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.
More simply, you can put parentheses around anything considered a "declarator" in the C++ grammar. (Loosely speaking, a declarator is a part of a declaration without the initial specifiers and types which contains one name.)
In your example, the identifier s
is a declarator, so you're allowed to put parentheses around it and the meaning doesn't change.
The reason for this, as the second quoted sentence hints, is that it can be necessary when things get more complicated. One example:
int * a [10]; // a is an array of ten pointers to int.
int ( * b ) [10]; // b is a pointer to an array of ten ints.
Just to add to the other answers; in the grammar summary for declarators (C++14 [dcl.decl]/4) you can find:
ptr-declarator:
noptr-declarator
noptr-declarator:
( ptr-declarator )
(I have omitted other details of the grammar). You can see from this that any declarator may be parenthesized and it would still match the same grammar rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With