Qt官方代码风格,可以参考一下。
不恰当用法:
int a, b;
char *c, *d;
纠正:
int height;
int width;
char *nameOfThis;
char *nameOfThat;
不恰当用法:
short Cntr; // 不明确的缩写
char ITEM_DELIM = ' ';
纠正:
short counter;
char itemDelimiter = ' ';
不恰当用法:
if(foo){
}
纠正:
if (foo) {
}
*
或&
之间使用单个空格,但在*
或&
与变量名称之间没有空格;char *x;
const QString &myString;
const char * const y = "hello";
不恰当用法:
char* blockOfMemory = (char* ) malloc(data.size());
纠正:
char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
不恰当用法:
if (foo) bar();
纠正:
if (foo)
bar();
不恰当用法:
if (codec)
{
}
else
{
}
纠正:
if (codec) {
} else {
}
static void foo(int g)
{
qDebug("foo: %i", g);
}
class Moo
{
};
不恰当用法:
if (address.isEmpty()) {
return false;
}
for (int i = 0; i < 10; ++i) {
qDebug("%i", i);
}
纠正:
if (address.isEmpty())
return false;
for (int i = 0; i < 10; ++i)
qDebug("%i", i);
if (address.isEmpty() || !isValid()
|| !codec) {
return false;
}
不恰当用法:
if (address.isEmpty())
qDebug("empty!"); // 这里不对称,容易造成误解
else {
qDebug("%s", qPrintable(address));
it;
}
纠正:
if (address.isEmpty()) {
qDebug("empty!");
} else {
qDebug("%s", qPrintable(address));
it;
}
不恰当用法:
// 多级嵌套语句没花括号容易逻辑错误
if (a)
…
else
if (b)
…
纠正:
if (a) {
…
} else {
if (b)
…
}
不恰当用法:
while (a);
纠正:
while (a) {}
不恰当用法:
if (a && b || c)
纠正:
if ((a && b) || c)
不恰当用法:
a + b & c
纠正:
(a + b) & c
switch (myEnum) {
case Value1:
doSomething();
break;
case Value2: // case后立刻进入下一个case
case Value3:
doSomethingElse();
Q_FALLTHROUGH();
default:
defaultHandling();
break;
}
不恰当做法:
if (thisOrThat)
return;
else
somethingElse();
纠正:
if (thisOrThat)
return;
somethingElse();
不恰当用法:
if (longExpression +
otherLongExpression +
otherOtherLongExpression) {
}
纠正:
if (longExpression
+ otherLongExpression
+ otherOtherLongExpression) {
}
ref: https://wiki.qt.io/Qt_Coding_Style