且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

代码风格

更新时间:2022-08-22 12:18:26

头文件的作用

申明将被程序用到的函数、变量和定义类型(包括:常量、类定义、模板定义……)

正确使用头文件

第1点: 

头文件中应该只包含函数和变量的申明,而不是定义。

例如:

在 main.cpp

 int mousex;

在 headers.h

 中

 extern int mousex;

如果多个cpp文件include了一个定义了变量的头文件,那么你将看到下面的错误信息

"error LNK2005: "int mousex" (?mousex@@3HA) already defined in headers.obj"

第2点:

在定义变量的地方初始化它们的值,而不是在申明它们的地方

例如:
在 main.cpp

 int mousey=0;

在 headers.h

 extern int mousey;

如果在头文件中初始化变量,那么编译器会认为这是一个定义,于是出现如下的错误信息:

"error C2086: 'int mousey' : redefinition"

第3点: 


为了避免重定义,***把头文件用以下的定义包含起来(现在编译器如VC++.net也可以用#pragma once代替)

#ifndef __HEADERS_H__

#define __HEADERS_H__

.

code

.

#endif __HEADERS_H__

匈牙利命名法

为了帮助程序员记忆变量的类型,Charles Simonyi发明了匈牙利命名法。使用它可以一目了然的在浩瀚的代码海洋中识别出变量的类型。


前缀

类型

例如

b

布尔型

bGameOver

by

Byte或Unsigned Char

byChoice

c

Char

cYesNo

cx / cy

尺寸

cxWidth

dw

DWORD, Double Word 或Unsigned Long

dwCounter

fn

函数

fnGetMeOver

h

Handle

hWindow

i

int (Integer)

iCounter

l

Long

lCounter

n

Short int

nChange

p

指针

pMakeChoice

s

String

sName

sz

以0结尾的字符串

szName

w

WORD Unsigned int

wCounter

x, y

坐标

x

文字间隔


文字的间隔对程序的结构和可读性非常重要

下面的两段程序哪个更容易读懂?

main()
{
char name[32]={"Red Cow Likes Milk"};
for(int t=0;t<16;t++)
{
t+=1;
for(int j=0;j<16;j++)
{
cout<<name[j];
}
cout<<name[t];
}
}

main()
{
char name[32] = {"Red Cow Likes Milk"};

  for( int t = 0; t < 16; t++ )
  {
    t+=1;
    for( int j = 0; j < 16; j++)
    {
      cout<<name[j];
    }
     cout<<name[t];
  }
}

接下来继续看

一行代码中的间隔

好的风格:
my.problem = FunkyG( my.bag + my.pipe * my.time);
不好的风格:
my.problem=FunkyG(my.bag+my.pipe*my.time);

变量名

选择最能说明变量作用的名字,如:
fMoneyAmount
fHitPoints
vDirection

但如果去掉字母中的元音后
fMnyAmnt
fHtPnts
vDirctn

非常混淆不是吗?还不如试试只用前三个字母
vDirctn = vDir

过长的变量或函数名也是不可取的(有时简直就是噩梦)

void RotationToFloatAngleDegreeDirection(float fRotation, Vector_t * vDirection); // 不好
void RotationToDirection(float fRotation, Vector_t * vDirection); // 好

void TheFunctionThatSetsAVariableAlwaysToZero(int * iVar); // 不好
void VarToZero(int * iVar); // 好

float TimeInCanadiaInHours(); // 不好
float Time_Canadia(); // 好

在程序中定义变量

全局变量:

议尽可能少用全局变量,因为不正确的是用很容易引起和局部变量的混淆,如:

int j=756;

void printJandQ(int Q)
{
  int j=0;
  cout << j << q;
}

局部变量的定义:

尽量不要在函数中间定义变量,这会导致可读性的下降和变量作用范围的混淆,在每个函数的开始处定义它的局部变量。(译者注:对于这条建议本人持保留态度)

静态分配和动态分配:

不好的风格:
struct DosFile_t
{
  char * name;
  int id;
}

如果一个字符串的长度有限制***使用静态分配,如下:

struct DosFile_t
{
  char name[8];
  int id;
}
在初始化变量时不要忘记付值:
不要认为一个变量在定义出来后就已经被付值为0了,记住手动付0给它们,如果是结构就用memset将其全部清0

int j=0;

DosFile_t * dfFileList;
dfFileList=(dfFile*)malloc(sizeof(dfFileList)*8);
memset(dfFile,0, sizeof(dfFileList)*8);