【发布时间】:2015-03-27 11:48:38
【问题描述】:
显式转换比只使用隐式转换更好吗?
例如,我有一个枚举...
/*This enum represents the various encryption types for wifi. For wifi capable devices, a bitwise & result of all supported encryption types should be returned.*/
typedef enum wifi_encryptionType {
/*Unknown encryption - default value, and for if wifi standard is ever expanded.*/
WIFIENCTYPE_UNKNOWN = 0,
/*No encryption - an open network.*/
WIFIENCTYPE_NONE = 1,
/*WEP encryption - all widths.*/
WIFIENCTYPE_WEP = 2,
/*WPA 1 with a preshared key using Temporal Key Integrity Protocol.*/
WIFIENCTYPE_WPA_PSK_TKIP = 4,
/*WPA 1 with a preshared key using Advanced Encryption Standard via CCMP. */
WIFIENCTYPE_WPA_PSK_AES = 8,
/*WPA 2 with a preshared key using Temporal Key Integrity Protocol.*/
WIFIENCTYPE_WPA2_PSK_TKIP = 16,
/*WPA 2 with a preshared key using Advanced Encryption Standard via CCMP.*/
WIFIENCTYPE_WPA2_PSK_AES = 32
} wifi_encryptionType;
我在结构中使用。
typedef struct {
char ssid[32];
wifi_encryptionType encryption;
wifi_mode mode;
} WifiNetwork;
我使用该结构字段的值作为函数调用的参数...
read_uint8(readBuffer, &network.encryption);
//read_uint8 takes a struct pointer containing some buffer info, and a uint8_t pointer.
我收到警告。
warning: passing argument 2 of 'read_uint8' from incompatible pointer type
expected 'uint8_t *' but argument is of type 'enum wifi_encryptionType *'
我明白警告的含义。 “请注意,读取 uint8_t 并将其放入 wifi_encryptionType 字段可能会在其中放置不映射到您声明的任何值的值。”
类型转换现在隐式完成。
将其设为显式演员表会更好吗?明确演员阵容有什么好处 - 还是有任何缺点?
【问题讨论】:
-
正如标签所指向的,没有“隐式转换”,只有“隐式转换”,即“显式转换” ”的定义。
-
@alk 是的,这是我的定义不匹配。我将代码视为“做”事情(它转换值)而不是让它发生(值以某种方式转换)。我的错。我修复了问题正文,并更新了问题标题以更具体地针对我的问题。
标签: c casting implicit-conversion