Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a declaration like int (x); or int (x) = 10;

If you look at the grammar for *declarator*s in §8/4 you'll notice that a noptr-declarator can be written as (ptr-declarator), that is, it can be written as (declarator-id), which validates declarations like the ones in the title. As matter of fact this code compiles without a problem:

#include <iostream> struct A{ int i;}; int (x) = 100; A (a) = {2}; int main() {     std::cout << x << '\n';     std::cout << a.i << '\n'; } 

But what is the purpose of allowing these parentheses when a pointer (to an array or to a function) is not involved in the declaration?

like image 947
Mao Avatar asked Nov 09 '14 19:11

Mao


People also ask

What is the purpose of variable declaration?

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable.

For what int x is used for?

Returns the largest integer less than or equal to the given value. The result is an integer data type.

What is the data type of variable x in the C statement int * x 10 ];?

x = 10 → It is assigning the value '10' to the variable 'x'. We can give any value to 'x'. We have given an integer value to the variable 'x' because we have already declared that the variable 'x' is an integer - int x .

What do mean by the statement int x in C++?

The keyword int tells C++ that this variable contains an integer value. (Integers are defined below.) The variable name is answer . The semicolon is used to indicate the statement end, and the comment is used to define this variable for the programmer.


1 Answers

The fact that this rule is applicable in your case is not deliberate: It's ultimately a result of keeping the grammar simple. There is no incentive to prohibit declarations such as yours, but there are great disincentives to complicate rules, especially if those are intricate as they are.

In short, if you don't want to use this needlessly obfuscated syntax, don't.
C++ rarely forces you to write readable code.

Surprisingly there are scenarios in which parentheses can save the day, though:

std::string foo();  namespace detail {     int foo(long); // Another foo      struct Bar     {         friend std::string ::foo(); // Doesn't compile for obvious reasons.          friend std::string (::foo)(); // Voilà!     }; } 
like image 82
Columbo Avatar answered Sep 22 '22 22:09

Columbo