Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

c++ - Inline function prototype vs regular declaration vs prototype

What's the difference between inline function and then main like so:

inline double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

vs just declaring a function regularly like:

double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

vs function prototype?

double cube(double);

int main( )
{
    cube(5);
}

double cube(double side)
{
   return side * side * side;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An inline function can be defined in multiple translation units (cpp file + includes), and is a hint to the compiler to inline the function. It is usually placed in a header which increases compile time, but can lead to faster code. It also allows the function to be used from many compilation units.

//cube.h
inline double cube(double side)
{
   return side * side * side;
}

//cube.cpp
int main( )
{
    cube(5);
}

Defining it regularly is the normal method, where it's (usually) defined in a cpp file, and linked against. It is not easily used from other compilation units.

//cube.cpp
double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

A prototype allows you to tell the compiler that a function will exist at link time, even if it doesn't exist quite yet. This allows main to call the function, even though it doesn't exist yet. Commonly, prototypes are in headers, so other compilation units can call the function, without defining it themselves. This has the fastest compilation time, and the function is easily used from other compilation units.

//cube.h
double cube(double);

//cube.cpp
int main( )
{
    cube(5);
}

double cube(double side)
{
   return side * side * side;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...