C/C++ 编程忠告

头文件:

1. <> 与 ""

#include <stdio.h>             // 仅用于标准库头文件
#include
"myHeader.h" // 仅用于非标准库头文件

2. 使用预编译宏避免重复引用

// header.h
//

#ifndef HEADER_H
#define HEADER_H

...

#endif // HEADER_H

  

  

变量修饰符:

int *p1 = NULL, *p2 = NULL ;
int *&ref = p1 ; // * 或 & 应紧邻变量名
int arr[10] = {0} ; // 数组标志应该紧邻变量名
delete []p ; // delete 数组是, 数组标志紧邻变量名
int c = '\0' ; // 定义同时初始化变量为其对应类型的空值
int x = 0, y = 0 ; // 在同一行定义相同数据类型

  

关于 const 的位置:

// Always put 'const' on left of type specifier and right on '*' specifier.
  // Just read from right to left.

const int cVar = 0 ;
const int *pcVar = NULL ; // Pointer to constant
int * const cpVar = NULL ; // Constant pointer

int const * pcVar = NULL ; // Bad

  

条件语句:

if (true)                      // Type bool should never compare with any other type.

// Write constant value on the left of condition. This style protecting your code from comparation to assignment.
'\0' == charVar ; // Type of char should compare with '\0'.
0 == intVar ; // Type of int should compare with 0.
// Type of float should ...???.
NULL == pointer ; // Any type of pointer can compare with NULL.

if (true == boolVar) // Bad! Never use true to compare with bool value.

  

函数:

void Fun1(const int arg1, const string &arg2) ;   // Always use const to modify input argument.
void Fun2(int &rtn1, string &rtn2) ; // If you use non-const reference, it's always means these value will change in funtion.

  
内存分配与释放:

  1. malloc and free are function while new and delete are operator.
  2. Only new and delete can create object because malloc and free don't call constructor and destructor.
  3. If delete an array, use [] to identify an array.
// malloc and free are function, should appear in pairing.
void *p = malloc(100) ;
free(p) ;
p
= NULL ; // Set pointer to NULL after free its memory.

// new and free are operator, should use in pairing.
int *p = new int ;
delete p ;
// delete []p if p is array.
p = NULL ; // Set pointer to NULL after release its memory.

  

 关于指针:

// Any pointer has size 4.
4 == sizeof(char *) ;
4 == sizeof(int *) ;
4 == sizeof(float *) ;

  

 关于变量:

  1.  如果将一个变量用作二进制模式. 请将其声明为 unsigned. (http://www.cnblogs.com/walfud/articles/2184406.html)
posted @ 2011-08-27 15:35  walfud  阅读(203)  评论(0编辑  收藏  举报