Search code examples
clinuxglibc

What's result of this ternary operator?


Can some one explain for me result of below ternary operator :

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

and this is full code :

#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;
}

and this is *get_num.h* header file content :

#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

* this code is according to part of linux library in (Linux Programming Interface BOOK)


Solution

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

    Is equal to:

    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;
    

    The ternary operator is the operator with lowest binding power after assignments and ,.