Returning Values from a void Function in C

  • Thread starter Spectre32
  • Start date
  • Tags
    Function
In summary: A. sum is a local variable of functionA.if you want to make the result of a + b available to another function, you can do it like this:void functionA(int a, int b, int *sum){ // *sum is the same as sum in the other example // it is a pointer that points to a memory location // you can change the value of a variable by dereferencing the pointer // and writing at the memory location that the pointer points to: *sum = a + b; // or you can write it like this: // a pointer is a variable
  • #1
Spectre32
136
0
Ok I am working on making a gambling program, that plays craps. Anyways, I have a question dealing with the basic structure of C. I thought that if you where going to return values, the function had to be something other than void. Well I'm looking through some of my professor past class activites, and he has values being returned but under void: See example



Code:
void  get_d_array( double array[], int *pnumgot )
/*
    purpose: get series of type double numbers from user
    goal state: return series of numbers in array[]
                ruturn number of values entered in *pnumgot
*/
{ // begin get_d_array
  // variable declaration
    int  i;   // loop index

  // ask user for number of lengths
    printf( "\nHow many values do you have to enter? ");
    printf( "\nNumber of values must be less than %d", MAXSIZE );
    printf( "\n    Number of values ==> " );
    scanf( "%d", pnumgot );

  // get values
    for( i = 0; i < *pnumgot; i = i+1 )
    { // begin for
        array[i] = 2.0*i+5;
    } // end for

} // end get_d_array

So... I mean values are being returned are they not? Yet this is under a void deceleration. Plus I thought that only one value can be returned.
 
Last edited:
Computer science news on Phys.org
  • #2
The function get_d_array is not returning anything. The return value of a function is the value that you get when you do something like:

foo=bar(biz);

Passing by reference is something different that a return value.
 
  • #3
It depends on what you mean by returned.

Normally that term refers to the single value passed by the return statement.

If you want to 'return' more than one value you do it the way your professor did. Instead of passing values TO the function by value, you pass them by reference.

That is what the * in front of pnumgot means. pnumgot is a pointer to a value, so if the function changes the data referenced by the pointer, the changed data is available to the calling routine when the function returns.

As the pointer can be indexed past any arbitary number of individual values, this allows a function to return an arbitary number of results.

When a value is passed to a function in the normal way, the function gets a fresh copy of the value, and even if it changes that value, the change is not available to the calling routine. But when you pass a value by reference, any changes made by the function are available to the caller.

The array is passed by reference too, as in C:

double array[]

means exactly the same as

double *array

which also means the same as

double* array
 
Last edited:
  • #4
Ahhh I see...So it's just passing reference. So for instance if i perfermed a calculation liek 2+2 and have sum = 2+2 then sume would be returned. Sum would alos fall into the category of not being declared also, correct?
 
  • #5
you have to specify what you want to return like this:

Code:
int sum(int a, int b)
{
  int answer;

  answer = a + b;

  return answer;
}
another function could use sum like this:
Code:
void main()
{
  int s;

  s = sum(2, 3);
}

the way to do the same without "returning" values but by passing values "by reference", would be like this:
Code:
// the * means that v is a pointer 
// a pointer is a variable that contains the address of another variable
void sum(int a, int b, int *v) 
{
  int answer;

  answer =  a + b;

  // write answer at the location in memory that  v "points to" :
  *v = answer; 
}
another function could use sum like this:
Code:
void main()
{
  int s;
  
  // you pass a pointer that tells sum where in memory s is
  // (&s means: the address of s):
  sum(2, 3, &s); 
}
 
  • #6
AH Ok yeah i was talking to my CS(com Sci) friend and he explained it all to me, but your explination further clairfies it. Also... for instance what your returing, can it be called by another function. EX:

Sum = 2+2

and i have a display function and I want it to display sum down in it. do i just have it in the main parameters of the function?
 
  • #7
Spectre32 said:
AH Ok yeah i was talking to my CS(com Sci) friend and he explained it all to me, but your explination further clairfies it. Also... for instance what your returing, can it be called by another function. EX:

Sum = 2+2

I do not know what you mean exactly. You can call a function and a function can return a value. You do not call a return value. When you want a function to have some value you pass it to the function via the function's arguments.

if you want to pass the sum of 2 and 2 to another function you simply do:

Code:
// this calls the function called sum 
//and assign the value that sum returns to a:
a = sum(2, 2);

// this passes the value of a to the function called other_function
// via other_function's first argument:
other_function(a, some_other_argument, and_a_third_perhaps);


Spectre32 said:
and i have a display function and I want it to display sum down in it. do i just have it in the main parameters of the function?

You can call the sum function from anywhere you want and assign the value it returns to a local variable.

Code:
display_function(argument1, argument2)
{
   int x;

   x = sum(34, 56);
   etc.
}
 
  • #8
Well when i said call I mean like, if i have sum = 2+2 in one function. and then Sum needs to be displayed in the next function, then can i just have sum defined up in the parameters.
 
  • #9
if you have a variable sum in one function like this:

Code:
void functionA(int a, int b)
{
   int sum;

   sum =  2 + 2;
    
   etc.
}

then the variable sum is only available within that function (it is only known between the { and }).

so if you need it in another function you will have to pass the value of the variable sum to the other function. Let's say that the other function, that needs sum, is called Display. Then you would pass the value of sum to Display like this:

Code:
void functionA(int a, int b)
{
   int sum;

   sum =  2 + 2;
   
   Display(sum);

   etc.
}
 
  • #10
Ok i keep getting this error when I try to build my program:

C:\Documents and Settings\jcs51.UPITT-USERS\Desktop\jcs51.cpp(128) : error C2061: syntax error : identifier 'total'


and it bring me to this line

Code:
if total = 2 && total = 3 
	{
		game_state = 1;
		point = 0;
	}
	else if ptotal = 7 && ptotal = 11 
	{
		game_state = 2;
		point = 0;


This I assume total is getting the approate value that it needs and there a problem witht he passing of it from my first function to this one. If anyone has any ideas I'd appericate them greatly.


this my my main function:

Code:
isplayheader();

  // algorithm
	// while loop for new game
	run_again = 'y';
	while (run_again == 'y' || run_again ==  'Y');
	{

		toss_dice(die_1,die_2,&total);
		result_one(total, point);
		display_toss_1(die_1, die_2, total, game_state);

		// while loop for the point comparison
		while (point != 0)
		{ 
			toss_dice(die_1,die_2, &total);
			result_two(total, point);
			display_toss_2(die_1, die_2,total, game_state, point);
		}
		// ask user to play again 
		printf( "\nWould you like to play another round?  (Y or N)"  );
		scanf("%c", run_again);
 
  • #11
these lines
Code:
if total = 2 && total = 3  
... 
else if ptotal = 7 && ptotal = 11
should be
Code:
if total == 2 && total == 3  
... 
else if ptotal == 7 && ptotal == 11

I also think there is something wrong here:
Code:
while (point != 0) 
		{  
			toss_dice(die_1,die_2, &total); 
			result_two(total, point); 
			display_toss_2(die_1, die_2,total, game_state, point); 
		}
this loop will never end if point is not already zero when you enter the loop, because no value is assigned to point (i.e the value of point does not change within this while loop)
 
  • #12
hmmm but point gets assigned a value from the previous alagorithm.
 
  • #13
You know that when you write something like

result_two(total, point);

then although the result_two() function can do what it wants with its copies of total and point, that's what they are - copies.

So if the value of total was say 5, then whatever result_two() does, the value will still be 5 when control returns to the line that follows the function call.

if you want the result_two() function to affect something local to the function call (say total) , you either have to do something like:

total = result_two(total, point);

or

result_two(&total, point);
 
  • #14
Yeah I know, that function is just taking that "total" and evaluating in a if/else statement.. total dosn't need to change at that current point in time.
 
  • #15
Ok ok Ok after some time I got it all pretyt much wokring ok now... I have narrow my problem down to this test.cpp i have created. Idealy what should be displayed by this function is two number between 1 and 6. If you attempt ot run this you get 0 and then some huge ass number... and no total. Any help would be appericated.
 
  • #16
Ok ok Ok after some time I got it all pretty much have everything working ok. Now... I have narrowed my problem down to this test.cpp, that I have created. Idealy what should be displayed by this function is two numbers between 1 and 6. If you attempt to run this you get 0 and then some huge ass number... and no total. Any help would be appericated.


Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 6




int main() /*
    purpose: generate a series of random numbers for the dice
    goal state: return total of number in ptotal
                ruturn number of values entered in ptotal
*/
{ // begin toss_dice
  // variable declaration
     int i, j;    // Loop index
	 double array_1,
			array_2,
			total;


	 srand( (unsigned)time( NULL ) );


	// begin loop for dice 1
   
	for (i = 0; i < 1; i++)
	 {
         array_1 = (int)  N * rand() / (RAND_MAX + 1.0);
		 
	 }
 

	// begin loop for dice 2
	for (j = 0; j < 1; j++)
	{
         array_2 = (int) N * rand() / (RAND_MAX + 1.0);
	}

	// compute total 
	total = array_1 + array_2;

	

 // end toss_dice

	printf( "\nYour dice rolls are as follows: %d Dice 1 %d Dice 2.",array_1,array_2);
	printf( "\nThe total is %d",total);
  //  declare win/lose, go again

return (0);

}
 
Last edited:
  • #17
You're using %d in the printf statements, which expects an integer argument, but the values you are passing are doubles.

You either have to change the %d to %f or cast the the doubles into ints, like this:

printf( "\nThe total is %d", (int)total);

By the way, your rand calculation is a little off.
 
  • #18
ahh crap i didn't even look at the format stuff.
 
  • #19
I fixed what you had suggested ceptimus, but i think i have deveopled another problem with this loop, and the way I'm going about this second part of my code:

Code:
do 
   { 
        
      toss_dice(&die_1,&die_2,&total); 
      point = total; 
      result_one(total, &point, &game_state); 
      display_toss_1(die_1, die_2, total, game_state); 

      //while loop for the point comparison 
      do 
      {    
         toss_dice(&die_1,&die_2, &total); 
         result_two(total, &point, &game_state); 
         display_toss_2(die_1, die_2,total, game_state, point); 
    
      } while ( point!= 0); 
      // ask user to play again 
      printf( "\nWould you like to play another round?  (Y or N)"  ); 
      scanf("%c", &run_again); 
   }   while (run_again == 'y' || run_again ==  'Y'); 

   return 0;

After some messing around I changed some things around in here:
Code:
//while loop for the point comparison 
      point2 = 1; 
      do 
      { 
         toss_dice_2(&die_1,&die_2, &total); 
         result_two(total, &point, &point2, &game_state); 
         display_toss_2(die_1, die_2,total, point,game_state); 
      }while (point2 != 0);

The whole while point != 0 thing dosn't work. Basicly this a a craps game, and if they user rdosn't win on the first try, the program is to cycle through the code until a decision has been reached. I comment all of that crap out invovling the second point stuff anf what not, and I got it to work OK with, with running once through. Now i just need to implelement this other stuff. Sooo I'm pretty sure the loop isn't working... but then why am I not gettting new Dice rolls?

picture of how the program is running http://home.comcast.net/~personalcomp1/Screen.bmp

I want to say that point2 needs to come out of that resualt_two, but I'm not really sure about how to go about that.
 
Last edited by a moderator:
  • #20
The do-while loop is ok, it will stop when point2 is zero, so somewhere whithin function result_two() you should assign a value to point2 (like *point2 = 0;).
 

FAQ: Returning Values from a void Function in C

What is a void function in C?

A void function in C is a function that does not return a value. It is used to perform a specific task or operation without returning a result.

How do you return a value from a void function in C?

In order to return a value from a void function in C, you can use the return statement followed by the value you want to return. However, this will convert the void function into a non-void function.

Can a void function return multiple values in C?

No, a void function can only return one value in C. If you need to return multiple values, you can use pointers or global variables to pass the values back to the calling function.

What is the purpose of a void function in C?

The main purpose of a void function in C is to perform a specific task or operation without returning a value. It can also be used for code organization and to improve readability and maintainability of the code.

Can a void function have parameters in C?

Yes, a void function can have parameters in C. These parameters can be used within the function to perform the desired task or operation, but they cannot be returned as a value.

Similar threads

Replies
1
Views
10K
Replies
4
Views
1K
Replies
3
Views
1K
Replies
3
Views
2K
Replies
3
Views
944
Replies
12
Views
1K
Back
Top