c++cformatclangclang-format

How to enable aligning multiple variable declarations


I want to set up my clang-format to format this:

double var1, var2,
    var3, var4;

into this:

double var1, var2,
       var3, var4;

Is there a way to achieve this?

If it cannot be set to align it, can you at least set it so it leaves it alone when you write it, like the second example?


Solution

  • As stated by heap underrun: don't declare your variables like this. You can read more about that e.g. in BARR-C:2018 Rule 8:

    char * x, y; // Was y intended to be a pointer also? Don’t do this.

    The cost of placing each declaration on a line of its own is low. By contrast, the risk that either the compiler or a maintainer will misunderstand your intentions is high.

    That beeing said: It is not possible to do what you want with Clang-Format. Yet. And probably never, due to the mentioned bad style.

    But as you also asked if it is possible to leave it as it is, you can do the following:

    // clang-format off
    double var1, var2,
           var3, var4;
    // clang-format on
    

    Note that all formatting will be disabled between those two comments. And that this will be laborious if you run into that situation often.

    You can read more about that in the Clang-Format Style Options.