簡體   English   中英

#在C語言中使用if-else邏輯定義

[英]#define with if-else logic in C

我正在根據Beej的《網絡編程指南》模擬客戶端/服務器交互。 server.c文件的開頭,我使用以下命令定義端口號:

#define PORT "21124"

但是,我將根據該文件創建多個服務器,並且我想根據某些if-else邏輯更改此常量。 C中是否有可以輕松完成此操作的功能,例如:

if (serverNumber == 1) {
  #define PORT "21124"
}
else if (serverNumber == 2) {
  #define PORT "12412"
}
else {
  #define PORT "12334"
}

這可能是重復的,但我沒有在搜索中看到。 我是C菜鳥。

“我想更改此常數”。 聽起來不對,是嗎?

因此,只需使用int port這樣的變量,並使用簡單的if-else語句塊或開關來分配其值。

您不應以這種方式使用#define 使用#if#elif#else的預處理器具有if-else邏輯,但是您必須意識到這實際上是對應用程序進行硬編碼。

您可以這樣做,但我也不建議這樣做。 只需使用變量或const因為它具有更好的類型安全性-不需要預處理器:

#define PORT_1   "21124"
#define PORT_2   "12412"
#define PORT_3   "12334"

if (serverNumber == 1) {
    port = PORT_1;
}
else if (serverNumber == 2) {
    port = PORT_2;
}
else {
    port = PORT_3;
}

您無法做正在嘗試的事情。

#define語句在編譯時處理。 在運行時基於變量的值使用不同的#define語句是沒有意義的。

您能做的最好的事情是:

#define PORT_1 "21124"
#define PORT_2 "12412"
#define PORT_3 "12334"

使用變量PORT並適當設置其值。

if (serverNumber == 1) {
  PORT = PORT_1;
}
else if (serverNumber == 2) {
  PORT = PORT_2;
}
else {
  PORT = PORT_3;
}

#define語句是C預處理程序的指令。 因此,在if語句中定義它們將不起作用。 您可以做的是這樣的:

#define ServerNumber 1
#if ServerNumber == 1
#define PORT 1234
#elif ServerNumber == 2
#define PORT 1235
#endif

或者,跳過一起使用#define ,並將此端口號指定為命令行選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM