Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of MyType(myVar) declaration in C++?

Tags:

c++

In c++11 standard we can declare variable in an unusual way. We can declare myVar as int(myVar); instead of int myVar. What is the point of this?

#include <iostream>
using namespace std;

int main() {
    int(myVar);
    myVar = 1000;
    cout << myVar << endl;
    return 0;
}

UPD Actually there is a certain reason why I asked this. What looked innocent just stopped to compile when we tried to port some code from MSVC C++03 to GCC C++11. Here is an example

    #include <iostream>
    using namespace std;

    struct MyAssert
    {
        MyAssert(bool)
        {
        }
    };

    #define ASSERT(cond) MyAssert(cond)

    void func(void* ptr)
    {
        ASSERT(ptr); // error: declaration of ‘MyAssert ptr’
                    // shadows a parameter #define ASSERT(cond) MyAssert(cond)
    }

    int main()
    {
        func(nullptr);
        return 0;
    }
like image 616
tim Avatar asked Jul 17 '14 11:07

tim


People also ask

Where is the right location for the declaration of variable in C program?

2.1. Before you can use a variable in C, you must declare it. Variable declarations show up in three places: Outside a function. These declarations declare global variables that are visible throughout the program (i.e. they have global scope).

What is declaration in C++?

A declaration specifies a unique name for the entity, along with information about its type and other characteristics. In C++ the point at which a name is declared is the point at which it becomes visible to the compiler.


2 Answers

Sure. I can even do this:

int (main)()
{
}

Parentheses serve to group things in C and C++. They often do not carry additional meaning beyond grouping. Function calls/declarations/definitions are a bit special, but if you need convincing that we should not be allowed to omit them there, just look at Ruby, where parentheses are optional in function calls.

There is not necessarily a point to it. But sometimes being able to slap on some theoretically unnecessary parentheses helps make code easier to read. Not in your particular example, and not in mine, of course.

like image 160
John Zwinck Avatar answered Sep 28 '22 08:09

John Zwinck


#include <typeinfo>
#include <iostream>

int     main(void)
{
  int   *first_var[2];
  int   (*second_var)[2];

  std::cout << typeid(first_var).name() << std::endl;
  std::cout << typeid(second_var).name() << std::endl;

  return 0;
}

Running this on my machine gives :

A2_Pi
PA2_i

The parenthesis in the declaration mostly serve the same purpose they do everywhere, group things that should be together regardless of the default priority order of the language. Of course parenthesis with only one element inside is equivalent to just typing that element except in cases where parenthesis are mandatory (e.g function calls).

like image 20
Drax Avatar answered Sep 28 '22 07:09

Drax