0

Which of the following code is likely to take less time to get executed?

/*Format 0*/
main(){
    int a=3,b=5;
    printf("%d",a*b);
}



/*Format 1*/
int mult(int a,int b){
    return a*b;
}
main(){
    printf("%d",mult(3,5));
}



/*Format 2*/
inline int mult(int a,int b){
    return a*b;
}
main(){
    printf("%d",mult(3,5));
}

As of now,I understand that the compiler inserts a snippet of the function everytime it encounters a function call to mult().Then which of the above is likely to be executed fastest?(If at all there is a differnce between their execution times in the range of nanoseconds or picoseconds?

3
Contributors
8
Replies
11
Views
5 Years
Discussion Span
Last Post by deceptikon
0

Compilers are not required to honor the inline keyword, so the first example is guarenteed to be the fastest. The other two examples may or may not be the same timing, depending on the compiler.

4

If at all there is a differnce between their execution times in the range of nanoseconds or picoseconds?

Execution is measured in "waste of programmer time" intervals that increase in direct proportion to the triviality of the statement.

Votes + Comments
Love it!!
ha ha ha... ha
0

Ah yes,the above statement being correct,which of the following is recommended ?

/*Inline function*/
inline int mult(int x,int y){
    return x*y;
}

OR

/*Macro-Preprocessor directive*/
#define mult(x,y) x*y

And why?

1

The first one. macros are evil creatures. The macro is wrong anyway. should be like this: #define mult(x,y)(x)*(y)

Edited by Ancient Dragon

0

No,that worked fine. By the way,in this simple operation,precedence should not be a concern.

0

The reason you need the parentheses in the macro is so that you can call the macro with something like this: mult(2+5,10/2) it will look like this when expanced
2+5*10/2 = 2 + 50/2 = 2 + 25 = 27, which is not the correct answer.

Inline functions don't have the above problem.

Edited by Ancient Dragon

0

Yeah,but here supplying only integers(not unevaluated arithmetic expressions) will help.

0

Yeah,but here supplying only integers(not unevaluated arithmetic expressions) will help.

Expecting someone, even yourself, to use a macro correctly is overly optimistic. The macro should be as dummy-proof as possible

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.