Does someone know what is wrong with my program in c?

69 Views Asked by At
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int sum(int);

int main() {

    printf("%d", sum(3));

    return 0;
}

int sum(i) {

    int num = 5;

    if (num == i)
    {
        return i;
    }

    else
    {
        return i + sum(i++);
    }

}

This is the program, I'm getting a segmentation error I don't know how to fix it

2

There are 2 best solutions below

4
pm100 On

here

return i + sum(i++);

i will only be incremented after sum returns. So you keep recursing forever and run out of stack.

You need

return i + sum(++i);

EDIT

as other have pointer out the order of which i gets evaluated and when it gets incremented etc is not defined. SO you need

 ++i;
 return i + sum(i);
0
Vlad from Moscow On

In C this statement

return i + sum(i++);

has undefined behavior.

Instead you need to write

 return i + sum( i + 1 );

Another problem is that the function declaration that is also its definition

int sum(i) {

is incorrect. You have to write

int sum(int i) {

Pay attention to that the function will have undefined behavior if the initial argument of the function will be greater than the magic number 5.