'make Clang-Format ignore comments for line break

Is it possible to tell Clang-Format to ignore comments for line break operations? The idea is to follow the style "the code is well formatted, even if comments exceed the line break margin". Code should not be split in multiple lines, if it does not exceed the margin, but the comment does.

e.g.

//desired behaviour:
short code = shortCode + 
        longlonglongCode;
short code = shortCode; //long comment without a line break

//not desired behaviour:
short code =
    shortCode;  //long comment without a line break


Solution 1:[1]

ReflowComments: (bool)

If true, clang-format will attempt to re-flow comments.

false:
// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
/* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */

true:
// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
// information
/* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
 * information */

Source

Use ReflowComments: true, when enabled it will add 1 space after // and brake comments when reach limit.

You can use PenaltyBreakComment to adjust.
E.g. block braking lines PenaltyBreakComment: 1000000000

Solution 2:[2]

A worked example of the penalties...

It's not complete optimal, but with clang-format-14, if you start with code like

QSqlDriver* driver() const;  // UNCERTAIN IF THIS IS OK to return the driver on the GUI thread, even if it lives in another
QString m_connection_name;  // written only in constructor; thread-safe access

then with

ReflowComments: false  # default is true for WebKit
PenaltyBreakComment: 300  # default
PenaltyBreakOpenParenthesis: 0  # default

you get this sort of irritation:

QSqlDriver* driver(
) const;  // UNCERTAIN IF THIS IS OK to return the driver on the GUI thread, even if it lives in another
QString
    m_connection_name;  // written only in constructor; thread-safe access

Whereas with this

ReflowComments:  true
PenaltyBreakComment: 300
PenaltyBreakOpenParenthesis: 0

you get

QSqlDriver*
    driver() const;  // UNCERTAIN IF THIS IS OK to return the driver on the
                     // GUI thread, even if it lives in another
QString
    m_connection_name;  // written only in constructor; thread-safe access

and finally with

ReflowComments:  true
PenaltyBreakComment: 0  # modified; was 300
PenaltyBreakOpenParenthesis: 1  # modified; was 0

you get

QSqlDriver* driver() const;  // UNCERTAIN IF THIS IS OK to return the
                             // driver on the GUI thread, even if it lives
                             // in another
QString m_connection_name;  // written only in constructor; thread-safe
                            // access

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gelldur
Solution 2 Rudolf Cardinal