简体   繁体   中英

How do I return value to main function without directly calling the function

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.

The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:

#include <iostream>
using namespace std;

int squarefree(int n);
int goodnumber(int sf);
int end(int gn);

int main() {
    // your code goes here
    int l,r;
    cin>>l;
    cin>>r;
    for(int p=l;p<=r;p++)
    {squarefree(p);}
    /*int ret=end(int gn); PROBLEM LIES HERE
    cout<<ret; */
    return 0;
}


int squarefree(int n){
    int i;
    for(int i=2;i<n;i++)
    {
        if((n%(i*i))==0)
        {
            cout<<"number not square free"<<endl;
            break;
        }
        else{
            cout<<"number square free"<<endl;
            goodnumber(n);
            break;

        }
    }
    return 0;
}


int goodnumber(int sf){
    cout<<"Sf is:"<<sf<<endl;
    int s=0,c=0,flag=0;
    for(int j=1;j<=sf;j++)
    {
        if(sf%j==0)
        {
            s+=j;
            for(int k=2;k<=j/2;++k)
            {
                if(j%k==0)
                {
                 c++;


                }
            }
        }
    }
    cout<<"s is:"<<s<<endl;
    cout<<"no.of prime numbers dividin s are:"<<c<<endl;
    for(int l=2;l<=c/2;++l)
    {
      if(c%l==0)
       {
          flag=1;
          break;
        }
    }
    if (flag==0)
      {cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
       end(s);

      }
    else
      {cout << "C is not a prime number"<<endl;

      }
      return 0;
}


int end(int gn)
{
    int sum=0;
    sum+=gn;
    cout<<"SUm of factors of the good number is:"<<sum<<endl;
    return sum;
}

The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.

If somehow, the value returned by end function can be fetched into main function, that would be great.

Look at all those int -returning functions that are always returning 0. You might be able to take advantage of that.

A trivial example:

#include <iostream>

int step3(int val)
{
    return val * val;
}

int step2(int val)
{
    return step3(val + 1);
}

int step1(int val)
{
    return step2(val * 2);
}

int main()
{
    std::cout << step1(1);
}

But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.

In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it's considered poor practice.

Some Examples:

// Returning the result of the next stage in the pipeline:
int g(int);

int f(int x)
{
  return g(x);
}

// Passing a variable by reference:
enum errcode { success, failure };

errcode sqr( int input, int& output )
{
  output = input * input; // This modifies the second variable the caller gave.
  return success;
}

// Storing in a temporary variable:
int stage2(int);

int stage1(int x)
{
   const int y = stage2(x);    // Store the result in a temporary.
   const int z = sqr(y);
   return z;
}

// Passing results through a global variable is a bad idea:
int necessary_evil = 0;  // Declared in global scope; should at least be
  // declared static if possible to make it visible only in this source file.
  // Namespaces are a fancier way to do something similar.

void kludge(int x)
{
   necessary_evil = x * x;   // The caller will check the global.
   return;
}

There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf() , strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM