What does it mean when the function in global namespace is declared as static C++? [duplicate]

扶醉桌前 提交于 2020-01-04 06:35:50

问题


Possible Duplicate:
What is a “static” function?

I have seen a function in a global namespace that is declared like this:

static int function_name(int a, double* p, int c, float * u)
{
     //do something with these arguments
}

What the static keyword means here?

EDIT: Now when I know what is for static, please explain what advantage gives the restriction of a function to be visible in a file only where it is declared? I mean why I should restrict my function visibility, what it gives to me?


回答1:


You would use a static function with the scope in the compilation unit when you really want the function with that name to be known only inside that compilation unit. A class or function that is not in that scope cannot accidentally call the function. (I'd have put this in a comment but I don't have privileges for that yet)




回答2:


The return value is not static int. The function is a static function returning an int.

See what is a static funciton




回答3:


It isn't the return value that's static, it's the function. It means that the function is visible within that compilation unit (= file, approximately) but not elsewhere.




回答4:


As already mentioned, static refers to the whole function, not its return type. I want to add that the use of the static keyword in this context is deprecated in C++. Anonymous namespaces are the better way to go.

namespace 
{
   int function_name(int a, double* p, int c, float * u)
}


来源:https://stackoverflow.com/questions/5300627/what-does-it-mean-when-the-function-in-global-namespace-is-declared-as-static-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!