Hello,

I am trying to write a function such as:

printValues(int nInts, int nFloats) ;

nInts describes the variable number of int values
passed, and nFloats describes the variable number of float
values passed.

Normally I would think of doing something like:

printValues(int num1, int num2, float num3....) ;

But nInts and nFloats needs to describe number of variables so printValues can be called with something like this in main:

printValues(4, 3, 3.3, 56.6) ;

I tried using enums, and unions but am unsure on how to implement them. Here is the code I've been messing with.

Any suggestions would be greatly appreciated.

#include <stdio.h>

union {
	int x; 
	float y; 
	char *z;
} U ;
 
typedef enum {
 
	INT, 
	FLOAT, 
	STRING
 
} Type ;
 
//void printValues(int nInts, int nFloats) ;
 
void printValues(int numI1, int numI2, float numF1, float numF2) ;

int main () {
 
	//printValues(4, 3, 55, 66, 77, 88, 34.5, 23.3, 56.6) ;
	printValues(4, 3, 3.3, 56.6) ;

}
//test to see it print correctly
void printValues(int numI1, int numI2, float numF1, float numF2) {
	
	printf("1: %d 2: %d 3: %f 4: %f \n", numI1, numI2, numF1, numF2) ;
}

/*void printValues(int nInts, int nFloats) {

	Type numInts = INT ;
	Type numFloats = FLOAT ;


}*/

Recommended Answers

All 2 Replies

void printValues(int numI1, int numI2, float numF1, float numF2) ;

int main () {
 
	printValues(4, 3, 3.3, 56.6) ;
}
//test to see it print correctly
void printValues(int numI1, int numI2, float numF1, float numF2) {
	
	printf("1: %d 2: %d 3: %f 4: %f \n", numI1, numI2, numF1, numF2) ;
}

What's wrong with this? It seems to work fine without that other stuff.
//edit: except that 56.6 prints out as 56.599998, for me

I have never used a union (never heard of it, actually, except in math.) Though after looking it up it seems like a pretty neat idea! The only time I've used an enum was when I wanted the data enumerated.

>Any suggestions would be greatly appreciated.
I get the impression you want a variable argument list. Something like this:

#include <stdio.h>
#include <stdarg.h>

void foo(int ints, int floats, ...)
{
  int sum_int = 0;
  double sum_float = 0;
  va_list args;

  va_start(args, floats);

  /* Get the ints first */
  while (--ints >= 0) {
    sum_int += va_arg(args, int);
  }

  /* Now get the floats */
  while (--floats >= 0) {
    sum_float += va_arg(args, double);
  }

  printf("%-5d%-6.2f\n", sum_int, sum_float);

  va_end(args);
}

int main(void)
{
  foo(1, 2, 5, 1.23, 2.34);
  foo(4, 3, 55, 66, 77, 88, 34.5, 23.3, 56.6);
  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.