0

I was using as my main IDE codeblocks, but I wanted to try visual studio. When I run the following code in Codeblocks (or an online C++ compiler) I get the right answer (output = 61), but when I put it in visual studio I get a weird answer (output= 90). Can somebody explain what is happening?

#include <iostream>

int sum(int *s, int sz);

int main()
{
    int arr[] = { 1,10,20,30 };
    int siz = sizeof(arr) / sizeof(int);
    int *ptr = arr;
    int output = sum(arr, siz);
    std::cout << "output = " << output << std::endl;
    return 0;
}

int sum(int *int_input, int n)
{
    if (n == 1)
    {
        return *int_input;
    }
    else
    {
        return *int_input + (sum(++int_input, --n));
    }
}


Thank you for the help :)

t.niese
  • 32,069
  • 7
  • 56
  • 86
  • Have you tried to step through your code using either codeblocks or visual studios debugger? What values are you getting vs what would you expect to get? – Cortex Mar 29 '20 at 16:01
  • See https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17 and decide whether you still need to ask the question. – Pete Kirkham Mar 29 '20 at 16:01
  • https://en.cppreference.com/w/cpp/language/eval_order – JohnFilleau Mar 29 '20 at 16:05
  • 1
    this clang warning should help you : `main.cpp:23:34: warning: unsequenced modification and access to 'int_input' [-Wunsequenced]` – URaoul Mar 29 '20 at 16:09

1 Answers1

2

Here you have unspecified behaviour in the next line

*int_input + (sum(++int_input, --n))

You cannot say for sure is dereferencing *int_input is first or incrementing ++int_input. To fix it, you need to rewrite code nextly:

*int_input + (sum(int_input+1, --n))
Midren
  • 460
  • 1
  • 7
  • Please be careful not to confuse new programmers by calling 'unspecified' behaviour 'undefined' – Pete Kirkham Mar 29 '20 at 16:01
  • The operations with side effects, `--n` and `++int_input` are not on the same scalar object. The difference isn't pedantic, it is going to hit a C++ programmer every week of their carreer. – Pete Kirkham Mar 29 '20 at 16:19