how does url within function body get compiled
Actually, http
followed by a colon is treated as a label by C++, which you can use in goto
statements (like goto http;
), and the rest (i.e //www.google.co.in
) is treated as single line comment. That's why it gets compiled.
See more,
void your_function()
{
http://www.google.co.in/
https://www.crazy_c++.com/
ftp://c++_is_fun.edu
//your code here
int i = 10 ; //atleast one line of code is needed here to get compiled!
}
By the way, I don't think the example you've written would get compiled. There should be at least one line of code after the url, only then it gets compiled on my PC. I'm using MSVC++ 2008.
In the compilation system, how does linker (ld) know who to link myprogram.o to?
Practically, over-simplified:
- You can compile a function into a library (ex.
.a
or.so
file on unix). - The library has a function body (assembly instructions) and a function name. Ex. the library
libc.so
hasprintf
function that starts at character number0xaabbccdd
in the library filelibc.so
. - You want to compile your program.
- You need to know what arguments
printf
takes. Does it takeint
? Does it takechar *
? Does it takeuint_least64_t
? It's in the header file -int printf(const char *, ...);
. The header tells the compiler how to call the function (what parameters does the function take and what type it returns). Note that each.c
file is compiled separately. - The function declaration (what arguments the function takes and what does it return) is not stored in the library file. It is stored in the header (only). The library has function name (only
printf
) and compiled function body. The header hasint printf(const char *, ...);
without function body. - You compile your program. The compiler generates the code, so that arguments with proper size are pushed onto the stack. And from the stack your code takes variable returned from the function. Now your program is compiled into assembly that looks like
push pointer to "%d\n" on the stack; push some int on the stack; call printf; pop from the stack the returned "int"; rest of the instructions;
. - Linker searches through your compiled program and it sees
call printf
. It then says: "Och, there is noprintf
body in your code". So then it searchesprintf
in the libraries, to see where it is. The linker goes through all the libraries you link your program with and it findsprintf
in the standard library - it's inlibc.so
at address0xaabbccdd
. So linker substitutescall printf
forgoto libs.so file to address 0xaabbccdd
kind-of instruction. - After all "symbols" (ie. function names, variables names) are "resolved" (the linker has found them somewhere), then you can run your program. The
call printf
will jump into the filelibc.so
at specified location.
What I have written above is only for illustration purposes.
Why can a url(http://) without commenting can compile without error?
Because it'll be treated as a label followed by a comment.
So you could later:
goto http;
If you turn on warnings: -Wall
it'll warn you gracefully:
In function ‘main’:
:2:5: warning: label ‘http’ defined but not used [-Wunused-label]
http://localhost
Are Python inner functions compiled?
To give a general explaination - assuming you have the following code in a module:
def outer(x=1):
def inner(y=2):
return x+y
When the file is parsed by python via compile()
, the above text is turned into bytecode for how to execute the module. In the module bytecode, there are two "code objects", one for the bytecode of outer()
and one for the bytecode inner()
. Note that I said code objects, not functions - the code objects contain little more than the bytecode used by the function, and any information that could be known at compile time - such as the bytecode for outer()
containing a ref to the bytecode for inner()
.
When the module actually loads, by evaluating the code object associated with the module, one thing which happens is an actual "function object" is created for outer()
, and stored in the module's outer
attribute. The function object acts as a collection of the bytecode and all context-relavant things that are needed to call the function (eg which globals dict it should pull from, etc) that can't be known at compile time. In a way, a code object is a template for a function, which is a template for execution of the actual bytecode with all variables filled in.
None of this involved inner()
-as-a-function yet - Each time you actually get around to calling outer()
, that's when a new inner()
function object is created for that invocation of outer, which binds the already-created inner bytecode object to a list of globals, including the value of x
as passed into that call to outer. As you can imagine, this is pretty fast, since no parsing is needed, just filling in a quick struct with some pointers to other already-existing objects.
Why does a plain URI written in c++ code work?
Identifier followed by : becomes a label in C++. Anything followed by // becomes a comment.
Why does a function body compile in a struct, but not in a trait?
How come this problem occurs in the trait, but not in its implementation for MyBTree?
These method signatures become more nuanced when you consider implementing BTree<T>
for a type that has a lifetime. My general advice for all lifetime errors involving a generic type parameter or a Self
type is: focus on the case when the type is a borrowed type.
The trouble with borrowed types is you can never have a reference with a longer lifetime than the data it refers to. The simplest example of this principle is:
fn f<'a, 'b>() {
// error[E0491]: in type `&'a &'b ()`, reference has a longer
// lifetime than the data it references
let _: &'a &'b ();
}
Rust forces us to guarantee that the data referred to by the reference outlives the reference, in this case 'b
outlives 'a
.
fn f<'a, 'b: 'a>() {
let _: &'a &'b ();
}
Now let's apply this to your BTree
situation by considering what goes wrong if T
is a borrowed type like &()
. First, looking at the following two methods which you placed in impl<T> BTree<T> for MyBTree<T>
. I have written the elided lifetimes explicitly to clarify the discussion.
impl<T> BTree<T> for MyBTree<T> {
fn left<'a>(&'a self) -> Option<&'a Self> { /* ... */ }
fn value<'a>(&'a self) -> Option<&'a T> { /* ... */ }
}
In order for the caller to invoke left
, they must know that Self
outlives lifetime 'a
. And in order for the caller to invoke value
they must know that Self
outlives lifetime 'a
and T
outlives lifetime 'a
(in order for &'a T
to be a meaningful type, as we saw above). The borrow checker will not let them call these methods unless those requirements are met, and so the implementation can assume those requirements are met.
Further, the borrow checker can see that if Self
outlives 'a
then also T
outlives 'a
because MyBTree<T>
contains a value of type T
.
This is why there was no problem implementing left
and value
within impl<T> BTree<T> for MyBTree<T>
. The caller and the MyBTree<T>
structure together guarantee that everything lives as long as we need.
Now in the case that we had these methods in the BTree<T>
trait definition.
trait BTree<T> {
fn left<'a>(&'a self) -> Option<&'a Self> { /* ... */ }
fn value<'a>(&'a self) -> Option<&'a T> { /* ... */ }
}
Things go wrong here because if the caller invokes left
they must know that Self
outlives 'a
, but they have not guaranteed that T
outlives 'a
. For example they could have T=&'b ()
for some totally unrelated shorter lifetime 'b
. As we saw above, that would make &'a T
equal to &'a &'b ()
which would not be a legal type.
The reason Rust is happy with value
defined in the trait is that the caller guarantees both Self
and T
outlive the input lifetime 'a
. The reason Rust is not happy with left
defined in the trait is that the caller guarantees only Self
outlives 'a
, not T
outlives 'a
which the implementation assumes.
And how come the compiler complains about the lifetime of T in the methods who ignore the T value -- while it works with the method
value
which does mention T in its return type?
Well the error is not about the return value, it is about the call to all()
. Look closely.
error[E0311]: the parameter type `T` may not live long enough
--> src/lib.rs:6:24
|
6 | match self.all() {
| ^^^
In order to call all()
, the caller is responsible for proving that the input and output types are valid types. But in the case that T
is something like &'b ()
, this may not be true. The all()
would return &'a &'b ()
so the borrow checker prevents the call.
We can fix this by making explicit the guarantees that our implementation assumes, in this case that T
outlives 'a
.
trait BTree<T> {
fn left<'a>(&'a self) -> Option<&'a Self>
where
T: 'a,
{
/* ... */
}
}
Why does a function declaration within another function compile and what does it do?
void updateAxisEnabled();
is a function declaration.
Sample:
#include <cstdio>
void a();
void b();
int main(void) {
a();
b();
return 0;
}
void a() {
void c(); // Declaration
c(); // Call it
}
void b() {
c(); // Error: not declared
}
void c() {
puts("Hello, world!");
}
Function inside function - every time?
You can check the bytecode with the dis
module:
>>> import dis
>>> def my_function():
... def little_function():
... print "Hello, World!"
...
...
>>> dis.dis(my_function)
2 0 LOAD_CONST 1 (<code object little_function at 0xb74ef9f8, file "<stdin>", line 2>)
3 MAKE_FUNCTION 0
6 STORE_FAST 0 (little_function)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE
As you can see the code for the inner function is compiled only once. Every time you call my_function
it is loaded and a new function object is created(in this sense the def little_function
is executed every time my_function
is called), but this doesn't add much overhead.
URI in source code
The compiler sees http:
as a label, and //www.google.com
as a comment.
javascript get function body
IF(!!!) you can get the toString()
, then you can simply take the substring from the first indexOf("{")
to the lastIndexOf("}")
. So, something like this "works" (as seen on ideone.com):
var test = function () {alert(1);}
var entire = test.toString(); // this part may fail!
var body = entire.substring(entire.indexOf("{") + 1, entire.lastIndexOf("}"));
print(body); // "alert(1);"
Related Topics
Outputting More Things Than a Polymorphic Text Archive
How to Get Hwnd of Window Opened by Shellexecuteex.. Hprocess
How to Do Performance Test Using the Boost Library for a Custom Library
Directx/C++ 3D Engine Programming: Learn Now, or Wait for Directx 12
Increase Stack Size When Compiling with Mingw
C++ Opengl Rotations and Calculations
Combining Two Lists by Key Using Thrust
Stl Random Distributions and Portability
Changing R's Seed from Rcpp to Guarantee Reproducibility
Is There Any 'Out-Of-The-Box' 2D/3D Plotting Library for C++
How to Make Sure That Std::Random_Shuffle Always Produces a Different Result
Use Templates to Get an Array's Size and End Address
Why Can't I Use Inheritance to Implement an Interface in C++
Why Is Copy Constructor Not Being Called in This Code
Compiling Code Containing Dynamic Parallelism Fails
C++ If Else If Not Working Properly
How to Swap Array-Elements to Transfer the Array from a Column-Like into a Row-Like Representation