What does ":=" refer to? - binary-search-tree

I'm looking at the algorithm for breadth-first sorting of a binary search tree, and there is a symbol used that I cannot understand. Funny enough, Google returns zero results.
// levelorder()
// q = empty queue
// q.enqueue(root)
// while not q.empty do
// node := q.dequeue() //Referring to this
// visit(node)
// if node.left != null then
// q.enqueue(node.left)
// if node.right != null then
// q.enqueue(node.right)
What is the operation being used here? I'm quite confused by this line.

The code you posted is pseudo code, and is not intended to be valid C++.
In C++, the assignment operator is =.
In other languages such as Ada, BCPL, Cecil, Dylan, E, Eiffel, Maple, Mathematica, Modula-3, Pascal, Pliant, Sather, Simula, Smalltalk, SML, the assignment operator is :=.
GNU make also uses := for a way of assigning.
Since the code you posted is a comment, it is not intended to be valid C++.
Here is a closer representation of the code you posted in valid C++:
#include <iostream>
#include <string>
#include <queue>
//A node might look like this:
struct Node{
Node* left;
Node* right;
};
//somewhere you have a node and a root
Node* node = new Node;
Node* root = new Node;
//a visit function is called in the pseudo code you posted
void visit(Node* node){
// ... code ...
return;
}
//here is what valid C++ that is similar to the pseudo code:
void levelorder(){
//empty queue
std::queue<Node*> q;
//add the root to the queue
q.push(root);
do {
visit(node);
if (node->left != nullptr){
q.push(node->left);
}
if (node->left != nullptr){
q.push(node->right);
}
}while(!q.empty());
return;
}
//I just added this main function so the whole code snippet compiles successfully
int main(){}

:= is assignment in pseudocode.
Or ADA. But that's kinda like psuedocode anyway.

It's inside a comment (per // prefix)... it's not compilable code and doesn't mean anything in C++.

It's not a C++ operator. It is used in some languages such as Pascal to mean the same thing as what an assignment = does.
See: Assignment operator (Computer science)

Related

ANTLR 3: passing value to Lexer (C target)

Is there a mechanism to pass a value to a lexer? (I'm working with C target in ANTLR 3)
Some other search results had suggested putting a function and var into the member area:
#members
{
bool read_flag;
void set_flag(bool b) {read_flag = b;}
}
however, that does not seem to work. The set_flag() is a global for the lexer, but not able to be called from outside
I want to be able to do something like this in the calling code:
//some input stream
pANTLR3_INPUT_STREAM input =
antlr3NewAsciiStringInPlaceStream((pANTLR3_UINT8)buf, len, NULL);
pmyLexer lxr = myLexerNew(input);
lxr->set_flag(true);
You can use the user pointer for that, which has been added exactly for this purpose:
lexer->pLexer->rec->state->userp = &context;
In my lexer I use this to store a reference to my RecognitionContext structure, which I then access via macros in my grammar:
#define PAYLOAD ((RecognitionContext*)RECOGNIZER->state->userp)->payload
#define SERVER_VERSION ((RecognitionContext*)RECOGNIZER->state->userp)->version
The structure is defined like this:
typedef struct {
long version;
void *payload;
...
} RecognitionContext;

Need clarification on the content given in the Linux Kernel by Robert Love

I am new in LKD and I was reading book by Robert Love. I stuck in understand one concept as follow.
Similarly, it is possible to iterate over a process’s children with
struct task_struct *task;
struct list_head *list;
list_for_each(list, &current->children) {
task = list_entry(list, struct task_struct, sibling);
/* task now points to one of current’s children */
}
Also I would be great if somebody explain the list_entry arguments work?
I am having difficult in understanding above code snippet specially list_for_each works.
list_for_each is a macro defined as
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
Since macros in C are expanded by textual substitution, the piece of code you cite becomes
for (list = (&current->children)->next; list != (&current->children); list = list->next) {
task = list_entry(list, struct task_struct, sibling);
/* task now points to one of current’s children */
}
This code walks a circular linked list starting at the node (&current->children)->next, until it comes back to (&current->children)->next.

Is there a way to wrap an ObjectiveC block into function pointer?

I have to provide a C-style callback for a specific C library in an iOS app. The callback has no void *userData or something similar. So I am not able to loop in a context. I'd like to avoid introducing a global context to solve this. An ideal solution would be an Objective-C block.
My question: Is there a way to 'cast' a block into a function pointer or to wrap/cloak it somehow?
Technically, you could get access to a function pointer for the block. But it's totally unsafe to do so, so I certainly don't recommend it. To see how, consider the following example:
#import <Foundation/Foundation.h>
struct Block_layout {
void *isa;
int flags;
int reserved;
void (*invoke)(void *, ...);
struct Block_descriptor *descriptor;
};
int main(int argc, char *argv[]) {
#autoreleasepool {
// Block that doesn't take or return anything
void(^block)() = ^{
NSLog(#"Howdy %i", argc);
};
// Cast to a struct with the same memory layout
struct Block_layout *blockStr = (struct Block_layout *)(__bridge void *)block;
// Now do same as `block()':
blockStr->invoke(blockStr);
// Block that takes an int and returns an int
int(^returnBlock)(int) = ^int(int a){
return a;
};
// Cast to a struct with the same memory layout
struct Block_layout *blockStr2 = (struct Block_layout *)(__bridge void *)returnBlock;
// Now do same as `returnBlock(argc)':
int ret = ((int(*)(void*, int a, ...))(blockStr2->invoke))(blockStr2, argc);
NSLog(#"ret = %i", ret);
}
}
Running that yields:
Howdy 1
ret = 1
Which is what we'd expect from purely executing those blocks directly with block(). So, you could use invoke as your function pointer.
But as I say, this is totally unsafe. Don't actually use this!
If you want to see a write-up of a way to do what you're asking, then check this out:
http://www.mikeash.com/pyblog/friday-qa-2010-02-12-trampolining-blocks-with-mutable-code.html
It's just a great write-up of what you would need to do to get this to work. Sadly, it's never going to work on iOS though (since you need to mark a page as executable which you're not allowed to do within your app's sandbox). But nevertheless, a great article.
If your block needs context information, and the callback does not offer any context, I'm afraid the answer is a clear no. Blocks have to store context information somewhere, so you will never be able to cast such a block into a no-arguments function pointer.
A carefully designed global variable approach is probably the best solution in this case.
MABlockClosure can do exactly this. But it may be overkill for whatever you need.
I know this has been solved but, for interested parties, I have another solution.
Remap the entire function to a new address space. The new resulting address can be used as a key to the required data.
#import <mach/mach_init.h>
#import <mach/vm_map.h>
void *remap_address(void* address, int page_count)
{
vm_address_t source_address = (vm_address_t) address;
vm_address_t source_page = source_address & ~PAGE_MASK;
vm_address_t destination_page = 0;
vm_prot_t cur_prot;
vm_prot_t max_prot;
kern_return_t status = vm_remap(mach_task_self(),
&destination_page,
PAGE_SIZE*(page_count ? page_count : 4),
0,
VM_FLAGS_ANYWHERE,
mach_task_self(),
source_page,
FALSE,
&cur_prot,
&max_prot,
VM_INHERIT_NONE);
if (status != KERN_SUCCESS)
{
return NULL;
}
vm_address_t destination_address = destination_page | (source_address & PAGE_MASK);
return (void*) destination_address;
}
Remember to handle pages that aren't required anymore and note that it takes a lot more memory per invocation than MABlockClosure.
(Tested on iOS)

About stl list::splice

I am facing a problem with splicing the list with itself. Note that I have gone through splice() on std::list and iterator invalidation
There the question was about two different lists. But my question is about the same list.
mylist.splice(mylist.end(), mylist, ++mylist.begin());
It seems that gcc 3.x is invalidating the moved iterator. So I suppose it is deallocating and allocating the node again. This does not make sense for the same list. SGI does tell that this version of splice should not invalidate any iterators. Is this a bug with gcc 3.x, if it is there any workaround?
In the mean time I was going through the stl_list.h file. But stuck with the transfer() function, I could not find a definition for these.
struct _List_node_base
{
_List_node_base* _M_next; ///< Self-explanatory
_List_node_base* _M_prev; ///< Self-explanatory
static void
swap(_List_node_base& __x, _List_node_base& __y);
void
transfer(_List_node_base * const __first,
_List_node_base * const __last);
void
reverse();
void
hook(_List_node_base * const __position);
void
unhook();
};
Do you have any idea where can I look for these function definitions?
This functions are in the libstdc++ sources, not the headers. In 3.4 it's in libstdc++-v3/src/list.cc
http://gcc.gnu.org/viewcvs/branches/gcc-3_4-branch/libstdc%2B%2B-v3/src/list.cc?view=markup
Have you tried compiling with -D_GLIBCXX_DEBUG ? That will enable the Debug Mode and tell you if you're using invalid iterators or anything else that causes the problem.
I just tried this simple test with GCC 3.4, with and without debug mode, and it worked fine:
#include <list>
#include <iostream>
#include <string>
int main()
{
std::list<std::string> l;
l.push_back("1");
l.push_back("2");
l.push_back("3");
l.push_back("4");
l.push_back("5");
l.push_back("6");
l.splice(l.end(), l, ++l.begin());
for (std::list<std::string>::iterator i = l.begin(), e = l.end(); i != e; ++i)
std::cout << *i << ' ';
std::cout << std::endl;
}
Modifying it further and debugging it I see that no element is destroyed and reallocated when doing the splice, so I suspect the bug is in your program. It's hard to know, as you haven't actually said what the problem is.

Offsetof macro with C++/CLI

The offsetof macro seems not to work under C++/CLI.
This works fine in unmanaged C++, but throws "error C2275: 'Entity' :illegal use of this type as an expression" error in CLI.
struct Property{
char* label;
PropertyTypes type;
unsigned int member_offset;
unsigned int position;
unsigned char bit_offset;
};
struct Entity{
...
bool transparent;
...
};
Property property = {"Transparent",
TYPE_BOOL,
offsetof(Entity, transparent),
0,
0}; // C2275 HERE
Does CLI have some replacement?
My guess would be that the compiler message boils down to: "offsetof" is not a known macro and if it was a function its parameters must not contain a typename.
Edit: As somebody pointed out in the comments, offsetof is actually part of the std lib. So what's missing is probably just
#include <cstddef>
Alternatively, you can use this macro implementation (taken from Win32/MFC headers):
#ifdef _WIN64
#define OFFSET_OF( s, m )\
(size_t)((ptrdiff_t)&reinterpret_cast<const volatile char&>((((s*)0)->m)) )
#else
#define OFFSET_OF( s, m )\
(size_t)&reinterpret_cast<const volatile char&>((((s*)0)->m))
#endif
Standard C++ already has an alternative; &Entity::transparent. You'll probably want to use templates when redesigning the Propery class. The type of a pointer-to-member is non-trivial.
You will need to provide the type of the object you are assigning to. Looks like there is some type-mismatch for the member in question.
See this for sample usage.
Just a shot in the dark and without a chance to double-check this - should
offsetof(Entity, transparent),
perhaps rather read
offsetof( struct Entity, transparent ),
???