Inline functions and pass by value to a function problem - c++

I've searched for the definition of an inline function, and basically all sources provide this answer:
"An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory."
I thought an inline function would be useful to work with functions and pass the value of an argument x, which is in main() scope, into function. That way, I thought the argument in main() scope would be affected and changed since the inline function does not copy the value but writes the actual code into the main() scope.
I expect the argument to be changed, yet it did not. Then what is the problem? Or is there something I've msised?

Related

calling a function inside header file [duplicate]

I have couple questions regarding some C++ rules.
Why am I able to call a function/method from outside the class in the namespace when I include the return type? (look at the namespace test2::testclass2 in the code below) i.e. this works:
bool b = testclass1::foo<int>(2);
whereas this doesn't: - (it doesn't even compile - compiler throws that this is function redeclaration)
testclass1::foo<int>(2);
C++ complains that it is a function redeclaration. Is that so?
This line:
bool b = testclass1::foo<int>(2);
gets called first before anything else. Is this because static methods get created always first before anything else in C++?
Where can I find those rules? I have a few C++ books at home, so if someone would be kind enough to either point out a book (and chapter or page) or direct me to a website I would greatly appreciate it.
Here below is the sample (partial) code that I tested at home with Visual Studio 2008:
class testclass1
{
public:
testclass1(void);
~testclass1(void);
template<class A> static bool foo(int i)
{
std::cout <<"in static foo";
return true;
}
};
namespace test2
{
class testclass2
{
public:
testclass2(void);
~testclass2(void);
};
bool b = testclass1::foo<int>(2);
}
EDIT:
A few people mentioned that I need to call this inside the function and this will work without any problem.
I understand that; the only reason I asked this question is because I saw this code somewhere (in someone's elses project) and was wondering how and why this works. Since I never really seen anyone doing it before.
Also, this is used (in multiple places) as a way to call and instantiate a large number of classes like this via those function calls (that are outside). They get called first before anything else is instantiated.
C++ is not Python. You write statements in functions and execution starts from the main method. The reason bool b = ... happens to work is that it's defining the global variable b and the function call is merely the initialization expression.
Definitions can exist outside functions while other statements can only exist inside a function body.
Why am I able to call a function/method from outside the class in the namespace when I include the return type? (look at the namespace test2::testclass2)
Your declaration of b is not inside a function, so you are declaring a global variable. If you were inside a function's scope, your second statement would work, but outside a function it makes no sense.
This also answers your second question.
Of course, you wouldn't be allowed to call it this way (i.e. not as a method of an object) if it weren't a static member function.
You can find the rules on e.g. Koenig lookup and template in the standard documentation -- good luck with navigating that! You're not mentioning which compiler you are testing, but I'm not entirely sure it's compliant!
As Mehrdad points out, you're declaring and initializing a global variable within the test2 namespace: this has nothing to do with static methods.
if you write this inside a function like below then it works without a problem. As mentioned above, you need to call these functions from within a function unless you are using the function to initialize a global variable ...
int main()
{
testclass1::foo<int>(2);
return 0;
}
1. First, a helpful correction: you said "...when I include the return type". I think you might be misunderstanding what the <int> part of testclass1::foo<int>(2) does. It doesn't (necessarily) specify the return type, it just provides a value for the template argument "A".
You could have chosen to use A as the return type, but you have the return type hard-coded to "bool".
Basically, for the function as you have written it you will always need to have the <> on it in order to call it. C++ does allow you to omit the <args> off the function when the type can be deduced from the function arguments; in order to get it to do that you have to use the type argument A in your function arguments. For instance if you declared the function this way instead then you could call it without the <>:
template<class A> static bool foo(A i);
In which case it you could call "foo(2)" and it would deduce A to be "int" from the number two.
On the other hand there isn't any way to make it deduce anything based on what you assign the function to. For template argument deduction it only looks at the arguments to the function, not what is done with the result of calling the function. So in:
bool b = testclass1::foo(2);
There is no way to get it to deduce "bool" from that, not even if you made A the return type.
So why doesn't the compiler just tell you "you needed to use <> on the function"? Even though you declared foo once as a template function, you could have also overloaded it with a non-template version too. So the compiler doesn't just automatically assume that you're trying to call a template function when you leave the <> off the call. Unfortunately having NOT assumed you were calling template-foo and not seeing any other declaration for foo, the compiler then falls back on an old C style rule where for a function that takes an int and returns an int, in a very old dialect of C you didn't need to declare that kind of before using it. So the compiler assumed THAT was what you wanted - but then it notices that template-foo and old-crufty-C-foo both take an int parameter, and realizes it wouldn't be able to tell the difference between them. So then it says you can't declare foo. This is why C++ compilers are notorious for giving bad error messages - by the time the error is reported the compiler may have gone completely off the rails and be talking about something that is three or four levels removed from your actual code!
2. Yes you're exactly right.
3. I find that the C++ references and whitepapers that IBM makes available online are the most informative. Here's a link to the section about templates: C++ Templates

inline this function, does make sense?

I have the next member function:
template <typename T>
inline T Foo::Read(const DWORD addr) const // Passing by value.
{
T buffer;
ReadProcessMemory(m_processHandle, (LPVOID)addr, &buffer, sizeof(T), NULL);
return buffer;
}
If I'm not wrong, when the compiler inlines a function, it avoids calling the function and put the code of the called function into the caller function.
So in the caller function (assuming an integer return type) I would want something like:
ReadProcessMemory(m_processHandle, (LPVOID)addr, &bufferOfTheCaller, sizeof(int), NULL);
I have three questions about this:
1) What would happen with the variable that we return from the function?
Isn't the declaration of the variable buffer performed in run time?
2) In this case ReadProcessMemory is a huge function from the WinAPI, should the compiler still able to inline this function?
3) What is the difference between leaving the member function defined inside the class definition and declare it with the keyword inline outside the class definition? If I want to use inline keyword, Do I have to put the inlined function in the same file .h or?
It's important to note that the inline keyword has nothing to do with inlining calls to the function. All it does is allow the function to be defined in multiple translation units, as long as all of the definitions are the same.
What the inline keyword does is let you define a function in a header file that will be included in multiple translation units. This may give the compiler a better opportunity to inline call to that function, since it has the full definition available in multiple translation units, but it is not a command or even a hint that you want the compiler to do so. The compiler will decide on its own if it should or shouldn't inline a call to any given function. There are compiler-specific extensions that you can use if you do want to force calls to a function to be inlined, but that is not what the inline keyword does.
With that out of the way, I'll add that the compiler inlining a function call doesn't change the rules of C++ at all. It isn't a textual replacement, like a preprocessor macro. The compiler will figure out how to insert the logic from the called function into the caller. At that point, things like C++ variables don't really exist. If your call looks something like this:
int someValue = myFoo.Read(someAddress);
then the compiler can easily transform that into something like this:
int someValue;
ReadProcessMemory(myFoo.m_processHandle, (LPVOID)someAddress, &someValue, sizeof(int), NULL);
due to the as-if rule. Both of those snippets result in the same observable behavior, so the compiler can freely transform between them.
What would happen with the variable that we return from the function?
It will be destroyed, because the return value was discarded by the function call expression.
Isn't the declaration of the variable buffer performed in run time?
Declarations happen at compile time.
In this case ReadProcessMemory is a huge function from the WinAPI, should the compiler still able to inline this function?
If the compiler knows the definition of the function, then it could expand it inline. Whether it should, or whether it will do so depend on many factors. Size of a function is a heuristic that may affect the choice that the compiler makes.
What is the difference between leaving the member function defined inside the class definition and declare it with the keyword inline outside the class definition?
In one case the definition is inside the class and in the other case it is outside. There is no other difference.
If I want to use inline keyword, Do I have to put the inlined function in the same file .h or?
If you want to define a member function inline, but want to define it outside of the class definition, then you must declare the function inline within the class definition - except a function template, which is implicitly inline.
If you want to define the member function within the class definition, then you don't need to explicitly declare it inline; it will be so implicitly.
If you want to not define the function inline, then you must define the function outside the class definition and must not use the inline keyword.
If I'm not wrong, when the compiler inlines a function, it avoids calling the function and put the code of the called function into the caller function.
Yes, but inline has little to do with that.
1) What would happen with the variable that we return from the function? Isn't the declaration of the variable buffer performed in run time?
The compiler, inlining or not, will have to reserve some space for buffer, typically on the stack.
In other words, there is no bufferOfTheCaller. If your function is inlined, buffer will be in the caller's stack frame; otherwise, it will be put in the callee's stack frame.
2) In this case ReadProcessMemory is a huge function from the WinAPI, should the compiler still able to inline this function?
It does not matter how big the implementation of ReadProcessMemory is, your code just performs a function call to it, which is tiny. An optimizing compiler is likely to inline your function.
3) What is the difference between leaving the member function defined inside the class definition and declare it with the keyword inline outside the class definition?
No difference.
If I want to use inline keyword, Do I have to put the inlined function in the same file .h or?
The inline keyword is not about inlining. If you want to put the definition of a function in a header file, you will likely need inline to prevent redefinition errors.

pointers-inline meaning? [duplicate]

This question already has answers here:
what is/are the purpose(s) of inline?
(9 answers)
Closed 8 years ago.
I have come across this while reading a program in C++
inline Controller* Get_it() { // ... bla bla
I don't understand what this means. Does this imply the definition of Get_it function? I have searched for files where Get_it function is defined, but didn't find it. I think that the syntax a* b means that b is pointer to point to objects of structure a, but there is no stucture Controller. There is though a class Controller defined somewhere else.
Thank you in advance people. I am new to C++ and I am trying to understand.
The function Get_it returns a Controller*. That's a pointer to a Controller, which is a type that must be declared somewhere above this point in the translation unit. The function is marked inline which is a hint to the compiler that it can inline the code, basically copying the function body into every place it is called from.
These two things are separate. The pointer is not inline, the function is.
The keyword inline affects what it being defined, and is only
applicable to functions. Formally, it allows (and in fact
requires) multiple definitions of the function. It is also
a "hint" to the compiler that it should try to generate the code
for the function directly at the call site, rather than to
generate a call elsewhere. (The motivation for the formal
definition is that the compiler typically cannot generate the
code inline unless it has access to the definition.)
First, you should get yourself a good book on C++. Secondly, that is a pointer to a Controller object (a class in memory). It is returned by the function and the function is defined inline, meaning that it will be copied entirely to the callsite wherever it is called.
The inline word is a suggestion to the compiler to do inlining where sensible, but because you seem to indicate the function is defined inside the class declaration, it will be inlined by the compiler automagically.
The inline keyword doesn't apply to the pointer (the return value of the function), but to the function itself. So here you declare (and define) an inline function which returns a pointer-to-Controller.
The inline keyword defines an method as inline1, no matter where it get's implemented. The signature above means, that the function Get_it() returns an pointer to an Controller object. The function itself is inline.
1 Inline means, that the method get's not addressed through an vtbl, but get's directly allocated in the object's memory, so that there is no indirection when calling the method on an object instance, but the object instance itself grows in memory size.

determining function declaration, definition and call

I came across a question regarding writing a code to determine unused functions in C++. We can use different data structures to determine unused functions. But before that, we need to parse the code. I have question related to parsing part, how we can differentiate functions declaration and definition and function-calls?
Like,
//function declaration without argument
fun1 ();
//function definition
fun1 () {
// code goes here
}
main () {
fun1 ();
}
Above declaration and call is looks same where as definition part is little bit different from declaration and call.
Other than above scenario, there are multiple scenario for calling a function and functions scope, like two classes having function with same name one function get called within member function (i.e. no explicit calling object required) OR function call using object so, need to understand object's type first to determine which function is actually called.
How can parsing implemented efficiently? How many parsing will required in above scenario?
This is how you can distinguish them:
//function definition
return_type fun1 (args) {
// code goes here
}
Note that function definition has a "return type" before the function name.
Also, note that a function declaration looks exactly the same as its definition. You don't actually need to distinguish them until you see either ; or {. That is the point in which you make the decision whether its a declaration or definition. In your particular application, you don't really care about it because you don't care what the function actually does.
Unfortunately for you, C++ is complicated. To determine which functions are useless, you actually need at least a basic semantic analysis. This includes at least the type system.
What is worse, is that some function may not necessarily be called directly, but through a virtual function. So your static analysis of the code shows only the parent's function getting called, while in reality it's the child's.

Inline functions in c++ - conditions

Under What condition an inline function ceases to be an inline function and acts as any other function?
The Myth:
inline is just a suggestion which a compiler may or may not abide to. A good compiler will anyways do what needs to be done.
The Truth:
inline usually indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules(especially w.r.t One Definition Rule) for inline are followed.
Under What condition an inline function ceases to be an inline function and acts as any other function?
Given the quoted fact there is a deeper context to this question.
When you declare a function as static inline function, the function acts like any other static function and the keyword inline has no importance anymore, it becomes redundant.
The static keyword on the function forces the inline function to have an internal linkage.(inline functions have external linkage)
Each instance of such a function is treated as a separate function(address of each function is different) and each instance of these functions have their own copies of static local variables & string literals(an inline function has only one copy of these ).
It's at the discretion of the compiler.
But some cases just can't be inlined, like:
Recursive functions
Functions whose address is referenced somewhere
Virtual functions (there are some exceptions thought)
That depends on the compiler optimization.
Different compilers have different rules to make the code more efficient. But if you declare a function as inline, the compiler tends to respect your decision as long as none of it's rules says different.
Remember that the compiler can change completely the execution path of a method. For example, consider the next situation:
int MyClass::getValue()
{
return someVariable;
}
At compile time, there is little difference between declaring this kind of function as inline or not. Probably the compiler will make the attribute partially public and code:
myInstance->getValue()
as
myInstance->someVariable
So it's more an aesthetical decision in most cases.