有人能给我解释一下下面三元算符的结果吗?

base = (flags & GN_ANY_BASE) ? 0 : (flags & GN_BASE_8) ? 8 :
(flags & GN_BASE_16) ? 16 : 10;

这是完整的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include "get_num.h"


static void
gnFail(const char *fname, const char *msg, const char *arg, const char *name)
{
fprintf(stderr, "%s error", fname);
if (name != NULL)
fprintf(stderr, " (in %s)", name);
fprintf(stderr, ": %s\n", msg);
if (arg != NULL && *arg != '\0')
fprintf(stderr, "
offending text: %s\n", arg);
exit(EXIT_FAILURE);
}
static long
getNum(const char *fname, const char *arg, int flags, const char *name)
{
long res;
char *endptr;
int base;
if (arg == NULL || *arg == '\0')
gnFail(fname, "null or empty string", arg, name);
base = (flags & GN_ANY_BASE) ? 0 : (flags & GN_BASE_8) ? 8 :
(flags & GN_BASE_16) ? 16 : 10;
errno = 0;
res = strtol(arg, &endptr, base);
if (errno != 0)
gnFail(fname, "strtol() failed", arg, name);
if (*endptr != '\0')
gnFail(fname, "nonnumeric characters", arg, name);
if ((flags & GN_NONNEG) && res < 0)
gnFail(fname, "negative value not allowed", arg, name);
if ((flags & GN_GT_0) && res <= 0)
gnFail(fname, "value must be > 0", arg, name);
return res;
}
long
getLong(const char *arg, int flags, const char *name)
{
return getNum("getLong", arg, flags, name);
}
int
getInt(const char *arg, int flags, const char *name)
{
long res;
res = getNum("getInt", arg, flags, name);

if (res > INT_MAX || res < INT_MIN)
gnFail("getInt", "integer out of range", arg, name);
return (int) res;
}

这是*get-num.h*头文件内容:
#ifndef GET_NUM_H
#define GET_NUM_H

#define GN_NONNEG       01
#define GN_GT_0         02


#define GN_ANY_BASE     0100
#define GN_BASE_8       0200
#define GN_BASE_16      0400

long getLong(const char *arg,int flags,const char *name);

int getInt(const char *arg,int flags,const char *name);

#endif

*此代码是根据(Linux编程接口手册)中Linux库的一部分编写的。

最佳答案

base = (flags & GN_ANY_BASE) ? 0 : (flags & GN_BASE_8) ? 8 :
    (flags & GN_BASE_16) ? 16 : 10;

等于:
if(flags & GN_ANY_BASE)
    base = 0;
else if(flags & GN_BASE_8)
    base = 8;
else if(flags & GN_BASE_16)
    base = 16;
else
   base = 10;

三元运算符是赋值后绑定功率最低且,的运算符。

关于c - 这个三元运算符的结果是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23032445/

10-11 22:06