C++ 註釋



C++ 註釋

程式註釋是可以在 C++ 程式碼中包含的解釋性語句。這些註釋可以幫助任何閱讀原始碼的人。所有程式語言都允許某種形式的註釋。

C++ 註釋的型別

C++ 支援兩種型別的註釋:**單行註釋**和**多行註釋**。任何註釋中可用的所有字元都被 C++ 編譯器 忽略。

C++ 註釋的型別將在下一節中詳細解釋

1. C++ 單行註釋

單行註釋以**//**開頭,一直延伸到行尾。這些註釋只能持續到行尾,下一行將開始一個新的註釋。

語法

以下語法顯示瞭如何在 C++ 中使用單行註釋

// Text to be commented

示例

在以下示例中,我們正在建立單行註釋 -

#include <iostream>
using namespace std;

int main() {
  // this is a single line comment
  cout << "Hello world!" << endl;
  // for a new line, we have to use new comment sections
  cout << "This is second line.";
  
  return 0;
}

輸出

Hello world!
This is second line.

2. C++ 多行註釋

多行註釋以**/***開頭,以***/**結尾。這些符號之間的任何文字都被視為註釋。

語法

以下語法顯示瞭如何在 C++ 中使用多行註釋

/* This is a comment */

/* 
  C++ comments can also
  span multiple lines
*/

示例

在以下示例中,我們正在建立多行註釋 -

#include <iostream>
using namespace std;

int main() {
  /* Printing hello world!*/
  cout << "Hello World!" << endl;
  /*
  This is a multi-line comment
  Printing another message
  Using cout
  */
  cout << "Tutorials Point";

  return 0;
}

輸出

Hello World!
Tutorials Point

語句中的註釋

我們也可以在 C++ 程式中的程式碼塊內註釋掉特定的語句。這兩種型別的註釋都可以做到這一點。

示例

以下示例說明了在語句中使用多行註釋 -

#include <iostream>
using namespace std;

int main() {
  cout << "This line" /*what is this*/ << " contains a comment" << endl;
  return 0;
}

輸出

This line contains a comment

示例

以下示例說明了在語句中使用單行註釋 -

#include <iostream>
using namespace std;

int main() {
  cout << "This line"  // what is this
       << " contains a comment" << endl;
  return 0;
}

輸出

This line contains a comment

巢狀註釋

/**/ 註釋中,// 字元沒有特殊含義。在 // 註釋中,/**/ 沒有特殊含義。因此,您可以將一種註釋“巢狀”在另一種註釋中。

示例

以下示例說明了使用巢狀在註釋中的註釋 -

#include <iostream>
using namespace std;
int main() {
  /* Comment out printing of Hello World:

cout << "Hello World"; // prints Hello World

*/
  cout << "New, Hello World!";
  return 0;
}

輸出

New, Hello World!

單行或多行註釋 - 何時使用?

單行註釋通常用於一般的短行註釋。這在我們需要在程式碼中為演算法提供一個小提示時很常見。

多行註釋通常用於較長的註釋行,在需要整個註釋行的可見性時。註釋越長,多行註釋所需的語句就越多。

註釋的目的

註釋在 C++ 中用於各種目的。註釋的一些主要應用領域如下所示

  • 表示程式中的一個簡短且簡潔的步驟,以便使用者更好地理解。
  • 詳細解釋程式碼中未明確表達的步驟。
  • 為使用者在程式碼本身中提供不同的提示。
  • 為了娛樂或消遣留下注釋。
  • 為了除錯目的暫時停用程式碼的一部分。
  • 為程式碼新增元資料以備將來使用。
  • 為程式碼建立文件,例如在 Github 頁面中。
廣告