Saturday, December 13, 2014

C言語で可変長引数をとる関数を、型安全に書く方法

C使

doublesumf

C使sumf
#include <math.h>
#include <stdarg.h>
#include <stdio.h>

static double sumf(double nfirst, ...)
{
  double r = 0, n;
  va_list args;

  va_start(args, nfirst);
  for (n = nfirst; ! isnan(n); n = va_arg(args, double))
    r += n;
  va_end(args);

  return r;
}

int main(int argc, char **argv)
{
  printf("%f\n", sumf(NAN)); /* => 0 */
  printf("%f\n", sumf(1., NAN)); /* => 1 */
  printf("%f\n", sumf(1., 2.5, 3., NAN)); /* => 6.5 */
  return 0;
}
NAN使NAN
2sumf(1, 1, NAN)double1

sumf
#include <stdio.h>

#define sumf(...)                                       \
  _sumf(                                                \
    (double[]){ __VA_ARGS__ },                          \
    sizeof((double[]){ __VA_ARGS__ }) / sizeof(double)  \
  )

static double _sumf(double *list, size_t count)
{
  double r = 0;
  size_t i;

  for (i = 0; i != count; ++i)
    r += list[i];

  return r;
}

int main(int argc, char **argv)
{
  printf("%f\n", sumf()); /* => 0 */2
  printf("%f\n", sumf(1.)); /* => 1 */
  printf("%f\n", sumf(1., 2.5, 3)); /* => 6.5 */
  return 0;
}
sizeofC使_sumfcountdoubleintdouble

HTTPH2Oh2o_concat使

H2O使C

H2O Advent Calendar 2014


1: sumf(1, 1, NAN)1
2: 0C99GCCClang

12 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. People are crazy about Startup but some bullshit Startup ideas also running these days.

    ReplyDelete
  4. If You Want Watch IPL Live Stream Then Visit www.crickspo.com, it also provide IPL Live ScoreCheck IPL Updates, IPL News, Ball By Ball Score, Men of the atch, men of the series, who won the toss today etc.

    ReplyDelete
  5. This is very interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your fantastic post. Also, I have shared your web site in my social networks!
    Regards - www.office.com/setup
    www.office.com/setup

    ReplyDelete
  6. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information.

    | norton.com/setup |
    | mcafee.com/activate |
    | office.com/setup |

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete

Note: Only a member of this blog may post a comment.