This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
 Documentation / Mathematica / The Mathematica Book / Practical Introduction / Files and External Operations  /

1.11.4 Generating C and Fortran Expressions

If you have special-purpose programs written in C or Fortran, you may want to take formulas you have generated in Mathematica and insert them into the source code of your programs. Mathematica allows you to convert mathematical expressions into C and Fortran expressions.

Mathematica output for programming languages.

  • Here is an expression, written out in standard Mathematica form.
  • In[1]:= Expand[(1 + x + y)^2]


  • Here is the expression in Fortran form.
  • In[2]:= FortranForm[%]


  • Here is the same expression in C form. Macros for objects like Power are defined in the C header file mdefs.h that comes with most versions of Mathematica.
  • In[3]:= CForm[%]


    You should realize that there are many differences between Mathematica and C or Fortran. As a result, expressions you translate may not work exactly the same as they do in Mathematica. In addition, there are so many differences in programming constructs that no attempt is made to translate these automatically.

    A way to compile Mathematica expressions.

    One of the common motivations for converting Mathematica expressions into C or Fortran is to try to make them faster to evaluate numerically. But the single most important reason that C and Fortran can potentially be more efficient than Mathematica is that in these languages one always specifies up front what type each variable one uses will beinteger, real number, array, and so on.
    The Mathematica function Compile makes such assumptions within Mathematica, and generates highly efficient internal code. Usually this code runs not much if at all slower than custom C or Fortran.