Home > front end >  Returning a function in main [closed]
Returning a function in main [closed]

Time:09-28

the purpose of the function it to take a number and flip it, means if the number is 1024 it will return 4201...

After creating the function I try to call it and check if it's actually working but when debugging it seems like it just skips the function and just print 1024.

What is my problem here?

On the top you can see the function and on the bottom there's the main() where I also call the function.

unsigned long reverse(unsigned int x)
{
    
    int current, newX = 0, i = 1;

    while (x != 0)
    {
        current = x % 10;
        x = x / 10;
        newX = newX * 10   current;
    }


    return newX;
}


int main()
{

    unsigned int x;

    printf("Enter number\n");
    scanf_s("%d", &x);


    reverse(x);

    printf("%d", x);

    return 0;
}

CodePudding user response:

You are not accessing the returned value of the function. To get the desired results do x = reverse(x);

CodePudding user response:

Take a parameter by reference and assign newX to it. Extra: some refactor with using cin, cout

#include <iostream>

void reverse(unsigned int & x)
{
  int current, newX = 0, i = 1;
  while (x != 0)
    {
      current = x % 10;
      x = x / 10;
      newX = newX * 10   current;
    }
  x = newX;
}

int main()
{
  unsigned int x;
  std::cout << "Enter number\n";
  std::cin >> x;
  reverse(x);
  std::cout << x;

  return 0;
}

... or use return value and reassign to "x" in main:

unsigned int reverse(unsigned int x)
{
  int current, newX = 0, i = 1;
  while (x != 0)
    {
      current = x % 10;
      x = x / 10;
      newX = newX * 10   current;
    }
  return newX;
}

int main()
{
  unsigned int x;
  std::cout << "Enter number\n";
  std::cin >> x;
  x= reverse(x);
  std::cout << x;

  return 0;
}
  • Related