-1
sum(int a,int b)
{
    int x;
    x = a+b;
}
int main()
{ 
    printf("%d",sum(2,3));
}

If i remove the x then it will return first parameter always, but I am not returning any value.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 5
    Because [undefined behavior](https://stackoverflow.com/q/32132574/10077). – Fred Larson Jun 06 '18 at 15:38
  • Upped as this question is nicely written with a compilable example. Remember, C gives you the ability to shoot yourself in the foot. That's why you need to follow the rules. And please use a compiler that will puke if a function doesn't have an explicit return type: that's been banned since C99. – Bathsheba Jun 06 '18 at 15:40
  • What program from ms office you used to compile this? – Petar Velev Jun 06 '18 at 15:43
  • @PetarVelev: Ahem! I have Microsoft Excel down as the best application ever written. – Bathsheba Jun 06 '18 at 15:43
  • @Bathsheba Then you most likely haven't seen much programs really – Edenia Jun 06 '18 at 15:44
  • @Edenia: I've seen enough. Sadly this ain't the site, but I can't resist. Care to state a couple of programs that you consider better? – Bathsheba Jun 06 '18 at 15:45
  • @Bathsheba Gladly: notepad, windows itself and this: http://i46.tinypic.com/293hj6w.jpg – Edenia Jun 06 '18 at 15:47
  • @Bathsheba Probably yes for its purpose. I had a different point there. – Petar Velev Jun 06 '18 at 15:47

2 Answers2

1

You are trying to make use of a function call return value and the function does not have a return statement in it.

Directly quoting C11, chapter §6.9.1 (for functions other than main(), Footnote)

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.


Footnote:

From chapter §5.1.2.2.3

[...] reaching the } that terminates the main function returns a value of 0.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
-1
int sum(int a,int b)
 {
     int x;
     x = a+b;
     return x;
 }
 int main()
 { 
     printf("%d",sum(2,3));
 }`

this is how your code should look, you're getting results sometimes as x is a local variable and its value persists on the stack until it's overwritten, so you may end up getting the value you want, or you may end up getting some garbage

bestestefan
  • 852
  • 6
  • 20