SliTaz SliTaz Forum

You are not logged in.

#1 2017-03-11 16:58:36

fsshl
Member
Registered: 2017-01-13
Posts: 18

Variable argument list in gcc,

I have tested a simple variable argument list in c program, my gcc 5.4 show different result as expected

-----------------------------------------

#include <studio.h>

#include <stdarg.h>

double average(int num,...) {

  va_list valise;

  double sum = 0.0;

  va_start(valise, num);

  for (int i = 0; i < num; i++) sum += va_arg(valise, int);

  va_end(valise);

  return sum/num;

}

int main() {

  printf("Average 2, 3, 4, 5, 6 = %f\n", average(5, 2, 3, 4, 5, 6);

  printf("Average 5, 10, 15 = %f\n", average(3, 5, 10, 15);

}

-----------------------------------------------------------------------

1674982.4

10

Which I assume should be

4

10

Plz help

Offline

#2 2017-03-12 04:06:01

mojo
Administrator
Registered: 2011-03-29
Posts: 2,173

Re: Variable argument list in gcc,

my.project.c : 

[c]#include <stdio.h>[/c]

[c]#include <stdarg.h>[/c]

[c]double average(int num,...) {[/c]

      [c]va_list valist;[/c]

      [c]double sum = 0.0;[/c]

      [c]int i;[/c]

     [c]va_start(valist, num);[/c]

     [c]for (i = 0; i < num; i++) {[/c]

       [c]sum += va_arg(valist, int);[/c]

     [c]}[/c]

     [c]va_end(valist);[/c]

     [c]return sum/num;[/c]

[c]}[/c]

[c]int main() {[/c]

    [c]printf("Average of 2,3,4,5,6 = %f\n", average(5,2,3,4,5,6));[/c]

    [c]printf("Average of 5,10,15 = %f\n", average(3,5,10,15));[/c]

[c]}[/c]

Compile:

[c]gcc my.project.c -o my.test[/c]

Execute:

[c]./my.test[/c]

Average of 2,3,4,5,6 = 4.000000

Average of 5,10,15 = 10.000000

Offline

#3 2017-03-14 07:41:49

fsshl
Member
Registered: 2017-01-13
Posts: 18

Re: Variable argument list in gcc,

the one I run/tested is on cygwin and its gcc5.4;  I wonder which platform you run your result?  in slitaz 5 and which gcc?

I tried same program on slitaz 5 and gcc 6.3, I got both numbers bad

--------------

Average of 2, 3, 4, 5, 6 = -114855950.400000

Average of 5, 10 15 = 1656347463.333333

---------------

do you know what may cause wrong? and how to fix it?  or what kind package I am missing download/install?

Offline

#4 2017-03-15 04:26:46

fsshl
Member
Registered: 2017-01-13
Posts: 18

Re: Variable argument list in gcc,

this problem solved,

due to some typo on my original c program

thanks your help

Offline

Registered users online in this topic: 0, guests: 1
[Bot] ClaudeBot

Board footer

Powered by FluxBB
Modified by Visman

[ Generated in 0.017 seconds, 7 queries executed - Memory usage: 1.53 MiB (Peak: 1.77 MiB) ]