Can functions be evaluated at compile time?

Consider the function below,

public static int foo(int x){
     return x + 5;
}

Now let's call him

int in = /*Input taken from the user*/;
int x = foo(10);     // ... (1)
int y = foo(in);     // ... (2)

Here the compiler may change

int x = foo(10);     // ... (1)

to

int x = 15;     // ... (1)

by calculating a function call at compile time, since the input to the function is available at compile time?

I understand that this is not possible during a call marked (2)because input is only available at run time.

I do not want to know a way to do this in any particular language. I would like to know why this may or may not be a sign of the compiler itself.

+4
source share
2 answers

C ++ has a method for this:

"constexpr" ++ 11, .

: return ( ), constexpr (++ 14 AFAIK).

static constexpr int foo(int x){
     return x + 5;
}

EDIT: ( ):

, , , .

/ : , .

( , AVR), , , .

( ).

EDIT:

constexpr - , . constexpr, .


, , ?

inline , .

, constexpr . , constexpr , , .

, constexpr , inline .

constexpr int foo( int a, int b, int c ){
  return a+b+c;
}

int array[ foo(1, 2, 3) ];

, .

struct Foo{
  constexpr Foo( int a, int b, int c ) : val(a+b+c){}
  int val;
};

constexpr Foo foo( 1,2,4 );

int array[ foo.val ];

foo.val - , .

, . , ( ).

, . , , .

+2

, . , .

" " " ", , " ", - ( undefined). , , . , , - , , , .

"enter", "" "" , , .

0

Source: https://habr.com/ru/post/1623197/


All Articles