Posts

Showing posts with the label initialization

Double Linked List in Common Lisp

5 I want to implement a simple double linked list in SBCL with the following key structure (defstruct element (value 0 :type fixnum) (next nil :type element) (prev nil :type element)) The problem is, that it's impossible to instantiate the first element, because neither next nor prev may be nil. Their type is element and so they have to be an instance. The problem is basically easy to fix if I remove the type property. But the fact is, that this part of the programm needs to be really fast, so I want to give the optimizer a chance to make the best out of it. Is there any other way to specify the type of the member AND to make them nil? Or better: Is there a way to create a start instance with next and prev referencing the instance itself? ...

Is this C++ member initialization behavior well defined?

Let's assume we have a class B that has a member which is default initialized to 42. This class knows how to print the value of its member. (It does so in the c'tor): struct B { B() : member(42) { printMember(); } void printMember() const { std::cout << "value: " << member << std::endl; } int member; }; Then we add a class A which receives a const reference to a B and asks B to print its value: struct A { A(const B& b) { b.printMember(); } }; Finally we add another class Aggregate that aggregates an A and a B. The tricky part is that object a of type A is declared before object b type B, but then a is initialized using a (not yet valid?) reference to b: struct Aggregate { A a; B b; Aggregate() : a(b) { } }; Consider the output of creating an Aggregate (I have added some logging to both c'tor and d'tor of A and B) (Try it online!): a c'tor value: 0 b c'tor value: 42 b d'tor a d'tor Am I right to assume that it...

Confusion about array initialization in C

In C language, if initialize an array like this: int a[5] = {1,2}; then all the elements of the array that are not initialized explicitly will be initialized implicitly with zeroes. But, if I initialize an array like this: int a[5]={a[2]=1}; printf("%d %d %d %d %d\n", a[0], a[1],a[2], a[3], a[4]); output: 1 0 1 0 0 I don't understand, why does a[0] print 1 instead of 0? Is it undefined behaviour? Note: This question was asked in an interview. TL;DR: I don't think the behavior of int a[5]={a[2]=1}; is well defined, at least in C99. The funny part is that the only bit that makes sense to me is the part you're asking about: a[0] is set to 1 because the assignment operator returns the value that was assigned. It's everything else that's unclear. If the code had been int a[5] = { [2] = 1 }, everything would've been easy: That's a designated initializer setting a[2] to 1 and everything else to 0. But with { a[2] = 1 } we have ...