if语句中的枚举比较在c中永远不是真的

时间:2016-01-09 07:32:29

标签: c if-statement enums

我正在ansi C开发一个程序,我有一些问题。 我有一个public class ServiceHandler { static String response = null; public final static int GET = 1; public final static int POST = 2; //Constructor with no parameter public ServiceHandler() { } /** * Making web service call * * @url - url to make request * @requestmethod - http request method */ public String makeWebServiceCall(String url, int requestmethod) { return this.makeWebServiceCall(url, requestmethod, null); } /** * Making service call * * @url - url to make request * @requestmethod - http request method * @params - http request params */ public String makeWebServiceCall(String urladdress, int requestmethod, String params) { URL url; String response = ""; try { url = new URL(urladdress); DataInputStream input; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setDoInput(true); conn.setDoOutput(true); if (requestmethod == POST) { conn.setRequestMethod("POST"); } else if (requestmethod == GET) { conn.setRequestMethod("GET"); } if (params != null) { OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } writer.write(result.toString()); writer.flush(); writer.close(); os.close(); } int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { response = ""; } } catch (Exception e) { e.printStackTrace(); } return response; }

enum

enum day { Monday = 'M', Tuesday = 'T', Wednesday = 'W' } 的{​​{1}}

2d array

稍后在if语句中使用:

days

但是,即使数组的每个元素都是typedef enum day availDays[numOfWeeks][daysOfWeek]; memset(theArray, Monday, sizeof(theArray)); ,该条件也永远不会计算为if ( theArray[0][0] == Monday ) { foo statements; } ,为什么会有任何想法?

1 个答案:

答案 0 :(得分:5)

这不起作用的原因是 sizeof(enum day) != 1 。所以你不能使用memset

这是因为虽然您将每个枚举值设置为char,但枚举的基础类型不是char。它(很可能)是int

这就是memset不起作用的原因。它将元素的每个字节设置为“M”。因此,每个元素将是值'M'的4个字节的“串联”。

假设小端,ASCII字符编码('M'0x4D)和sizeof(int) 4,数组在memmory中应如下所示:

0x4D0000004D000000...

memset将其设置为:

0x4D4D4D4D...

唯一的解决方案是遍历数组并单独设置每个元素

for (i...)
    for (j...)
        theArray[i][j] = Monday;

故事的道德:仅对memset个缓冲区使用charchar是标准要求的唯一类型,具有完全匹配的大小。

虽然问题是关于C,但最好知道C++中有谁需要这个,自C++11以来您可以指定enum的基础类型:

enum Day : char {
   ...
};

sizeof(Day) == 1; // true