假设我在整个程序中经常使用一些字符串(用于存储状态和类似的东西).字符串操作可能很昂贵,所以无论何时解决它们我都想使用枚举.到目前为止,我已经看到了几个解决方案:
typedef enum {
STRING_HELLO = 0,
STRING_WORLD
} string_enum_type;
// Must be in sync with string_enum_type
const char *string_enumerations[] = {
"Hello",
"World"
}
Run Code Online (Sandbox Code Playgroud)
我经常遇到的另一个:
typedef enum {
STRING_HELLO,
STRING_WORLD
} string_enum_type;
const char *string_enumerations[] = {
[STRING_HELLO] = "Hello",
[STRING_WORLD] = "World"
}
Run Code Online (Sandbox Code Playgroud)
这两种方法的缺点是什么?还有更好的吗?
当第一个条件为假时,ruby是否会停止评估if语句?我不断地得到undefined method `ready' for nil:NilClass>如song = nil.
if !song.nil? && song.ready && !song.has_been_downloaded_by(event.author)
song.send_to_user(event.author)
nil
elsif !song.ready
"The song is not ready yet. Try again once it is."
elsif song.has_been_downloaded_by(event.author)
"Yo, check your private messages, I've already sent you the song."
else
'Song with such index does not exist.'
end
Run Code Online (Sandbox Code Playgroud) 我是一个非常新的C#,这是我第一次使用列表做任何事情,所以这可能是一个非常愚蠢的问题......我正在尝试将文件中的数据读取到由Tourist对象组成的列表中.据我所知,我需要tourists在添加对象之前将一些内容分配给列表,但我不知道该怎么做.
class Tourist
{
public string FirstName { get; set; }
public string LastName { get; set; }
public double Contributed { get; set; }
public Tourist(string firstName, string lastName, double money)
{
FirstName = firstName;
LastName = lastName;
Contributed = money * 0.25;
}
}
class Program
{
static void Main(string[] args)
{
List<Tourist> tourists = new List<Tourist>();
ReadData(out tourists);
}
static void ReadData(out List<Tourist> tourists)
{
const string Input = "..\\..\\Duomenys.txt";
string[] lines = …Run Code Online (Sandbox Code Playgroud) 考虑这个C程序:
#include <poll.h>
#include <stdio.h>
#include <unistd.h>
#define TIMEOUT 500 // 0.5 s
#define BUF_SIZE 512
int fd_can_read(int fd, int timeout) {
struct pollfd pfd;
pfd.fd = fd;
pfd.events = POLLIN;
if (poll(&pfd, 1, timeout)) {
if (pfd.revents & POLLIN) {
return 1;
}
}
return 0;
}
int main(int argv, char **argc) {
int fd;
size_t bytes_read;
char buffer[BUF_SIZE];
fd = STDIN_FILENO;
while (1) {
if (fd_can_read(fd, TIMEOUT)) {
printf("Can read\n");
bytes_read = read(fd, buffer, sizeof(buffer));
printf("Bytes read: %zu\n", …Run Code Online (Sandbox Code Playgroud) 我有一个程序,根据编译时定义提供不同的功能.我定义OPT_STRING了包含所有可能的命令行参数(用于getopt_long).我一直在寻找一个聪明的根据编译时定义来改变它的定义.我想出了这个:
#define OPT_STRING "haspvb"
#ifdef HAVE_WIFI
#define OPT_STRING OPT_STRING "mw" // => "haspvb" "mw"
#endif // HAVE_WIFI
#ifdef HAVE_IMEI
#define OPT_STRING OPT_STRING "i" // => "haspvb" "mw" "i" or "haspvb" "i"
#endif // HAVE_IMEI
Run Code Online (Sandbox Code Playgroud)
但是,这会导致编译错误:
error: "OPT_STRING" redefined
Run Code Online (Sandbox Code Playgroud)
是否有某种"宏观魔法"来实现我想要做的事情?
每当我select在 C 中看到一个调用时,我看到它写成:
select(sock_fd + 1, &fdset, NULL, NULL, &tv)
Run Code Online (Sandbox Code Playgroud)
或类似的东西。增加文件描述符的含义是什么?