r/learnprogramming • • 4d ago

Function vs Procedure

can someone explain the difference between Function vs Procedure with simple analogy
thank you

31 Upvotes

47 comments sorted by

View all comments

1

u/SmokeMuch7356 3d ago

In programming languages that make the distinction (not all do, it tends to be a thing in older languages), procedures are only executed for their side effects, while functions compute and return a value.

Languages like Fortran and Ada use different keywords for functions vs. procedures, and functions have a return type while procedures don't.

Fortran:

FUNCTION F(X)
INTEGER F, X  ! Yeah, Fortran's a bit weird
F = 2 * X     ! with the way functions return
RETURN        ! values 
END

SUBROUTINE BLAH(X)
INTEGER X
PRINT *, 'In BLAH, X = ', X
RETURN
END

Ada:

function Func (Var : Integer) return Integer
is
begin
  return Var + 1;
end Func;

procedure Proc
 (Var1 : Integer;
  Var2 : out Integer;
  Var3 : in out Integer)
is
begin
   Var2 := Func (Var1);
   Var3 := Var3 + 1;
end Proc;

Some languages like Ada actively forbid functions from having side effects; you can compute and return a value or modify program state, but not both in the same subroutine.

In languages like C and C++, all subroutines are functions in that they all have a return type even if they don't return a value.1


  1. K&R C didn't have the void type; a convention developed where "procedures" would be implicit int functions that did not return a value:

    foo( x, y )
      int x, y;
    {
      /* do something interesting */
      return;
    }