![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Mar 2005
Posts: 7
Rep Power: 0
![]() |
Returning a value from a variable to the main function
Hi, I am having a big little problem to return to the main function, the value of a sum operation. As you can see in the code, all I want to do is to return the data contained in the 'res' variable (n1 + n2) to the main function.
There I call the function SUM through a call function "SUM (int res); " to display in the end of the main function, the result of the sum: n1 + n2, but I get the following errors: test.c: In function `main': test.c:15: error: syntax error before "int" So what I am doing wrong? What I need to do to sucessfully be able to return the data contained in the res variable to the main function to finally see the result of the mathematical operation? Thanks in advance. [code]#include <stdio.h> int SUM (int n1, int n2); main () { int n1, n2, i; while (5 == 5) { printf ("To close the program, type 0: "); scanf ("%d", &i); if (i == 0) break; printf ("Type the numbers that should be used to do the sum: "); scanf ("%d %d", &n1, &n2); SUM (int res); } } int SUM (int n1, int n2) { int res; res = n1 + n2; printf ("The result is: %d", res); return res; } |
|
|
|
|
|
#2 |
|
Professional Programmer
Join Date: Nov 2004
Posts: 250
Rep Power: 5
![]() |
>while (5 == 5) {
This is strange. Not only that you used <constant> == <constant>, but because you chose 5 as the constant. A more conventional way to create an infinite while loop is while ( 1 ) {
/* Body */
}A function call does not declare parameters, it takes arguments: SUM (n1, n2); #include <stdio.h>
int SUM (int n1, int n2);
int main ()
{
int n1, n2, i;
while (1) {
printf ("To close the program, type 0: ");
scanf ("%d", &i);
if (i == 0) break;
printf ("Type the numbers that should be used to do the sum: ");
scanf ("%d %d", &n1, &n2);
SUM (n1, n2);
}
}
int SUM (int n1, int n2)
{
int res;
res = n1 + n2;
printf ("The result is: %d", res);
return res;
} |
|
|
|
|
|
#3 |
|
Professional Programmer
Join Date: Mar 2005
Location: Glasgow, Scotland
Posts: 328
Rep Power: 4
![]() |
Nice solution. I just thought I'd add; another conventional way to do an infinite loop is for (;;), which arguably is even clearer since it doesn't even have the 'dummy condition' constant 1.
Last edited by mackenga; Apr 28th, 2005 at 8:11 AM. Reason: Darn smileys... :) |
|
|
|
|
|
#4 |
|
Programming Guru
![]() ![]() ![]() |
Speaking of infinite loops... here's the "cool" way...
#define EVER ;; for (EVER) { ... }
__________________
http://jasonpowers.net "There are a thousand hacking at the branches of evil to one who is striking at the root." |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|