Writing “Hello World” program!

Sometimes we get questions which are silliest but have to attempt since the situation demands it (interviews, presentations, professor’s lecture..). One of those silly (of almost “0” importance and usability in life) questions is “How many ways can you write a ‘Hello, World!’ program in C/C++?”.

For those, who want me to write some specification of the program – task is to write a program to print on console a string “Hello, World!”. Well, lots and lots of answers —

int main() { printf(“Hello, World!\n”); } /* C Example */

int main() { std::cout << “Hello, World!” << endl; } // C++ Example

int main() { if(printf(“Hello, World!\n”)) {} } // C; without semicolon

int main() { while(!printf(“Hello, World!\n”)) {} } // C; without semicolon

following, I came through while re-reading stroustrup is writing a program using iterators (Chapter3;Iterators and I/O). This is nothing new and just a iteratorized manifestation of example II above.. but yes, different clothing!

ostream_iterator<string> oo(cout);
int main() { *oo = “Hello, “; ++oo; *oo = “World!\n”; }

Advertisements

Is it possible that I call function with NULL object without segfaulting?

Oh yes it is!

While debugging my project at work I came across this interesting piece. Inspector (watch or expressions in visual studio) showed me the variable with which the function was being called was NULL (0x0) i.e. considered invalid and still the function call went fine. This variable was initialized later. I thought this should be one of the weird things that compilers and IDEs do sometimes but no it was not like that and i observed the same behavior with restarting the IDE and changing the compiler.

If your class does not have data associated with it (member variables) then its functions can be called without allocating any memory to it.

e.g. following class and example:

class A
{
public:
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();
}

Then for MS compiler cl.exe, you can call a function from a NULL object as far as you don’t access the variable even if you have defined it.

class A
{
int i;
public:
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();
}

This will SEGFAULT.

class A
{
int i;
public:
void printA() { cout << “A\n” << i; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();

and yes, you can do this in C++ and not Java.

Orthogonality and its importance in software development

I’ve been lately reading The Pragmatic Programmer by Andrew Hunt & David Thomas. Been onto a chapter about decoupling requirement in the development of software, I thought of putting few lines on the weblog. Orthogonality is derived originally from Geometry where it is meant to illustrate two lines which meet at right angles and hence are mutually independent moving in all directions. In software, orthogonality refers to the independence between the modules of the software. e.g. user interface of a software should not have any dependence on Database schema. Decoupling, if not met properly while designing software, can lead to disaster in code maintenance. A decoupled code is better for maintenance because of numerous reasons –

1. Changes are localized and hence development and testing time (and cost) are reduced. Quality also improves since better division of work is possible.

2. Problems are also localized. An issue in one module does not affect other modules and hence fix requires to be done their only (or whole module can be replaced by another implementation altogether).

3. There is more possibility of smaller independent teams (which is ideal for a better coordination)

An interesting introduction into orthogonality is the advent of Aspect Oriented Programming (AOP), a research project at Xerox Parc. As Object oriented programming focusses on the objects and their interaction, Aspect oriented programming focusses on aspects (concerns). AOP lets you express a behavior which would otherwise be distributed throughout the source code. The most obvious example would be logging. Log messages are normally generated by sprinkling explicit calls to some log function throughout the code. With AOP, you implement logging orthogonally to the things being logged. Using the AOP for Java, you could write a log message while entering any method of Class Fred by coding the aspect –

aspect Trace {
advise * Fred.*(..) {
static before {
Log.write(” -> Entering ” + thisJointPoint.methodname);
}
}
}

If you weave this aspect in your code then log messages will be generated and if you don’t, they won’t. Either way, your original source is unchanged.

Towards the end of the discussion is a challenge: Consider large GUI-oriented tools typically available on Windows and small but combinable command line tools used on shell prompts. Which do you think are more orthogonal in design?

What do you think?

return and exit from main: difference

What is the difference between returning from main with some exit code and calling exit giving the exit code as parameter ?

Basically the difference between following programs !

//ret.c
int main()
{
return 43;
}

//exit.c
int main()
{
exit(43);
}

well, there are three ways for the processes to exit: –

1. Voluntary exit (implicit)
2. Voluntary exit (explicit)
3. Involunatary exit

Voluntary exit can be implicit e.g. in case of return and explicit e.g.
in case of a call to exit(). Involuntary exit is like being killed by a
third process, receiving a SIGSTP signal (or other signals whose default ot set
behavior results in terminating the process).

+ ‘return’ is an implicit voluntary termination of process
+ ‘exit’ is an explicit voluntary termination.

Note: both calls actually execute code in the function ‘do_exit’ ultimately.

I also tried writing above programs and inspecting the assembly just to know if
there is any difference in the code ultimately. Here are they:

[ used ‘objdump -d’ function and showing here only the function ‘main’ disassembly]

//ret.o – main
080482f4 :
80482f4: 55 push %ebp
80482f5: 89 e5 mov %esp,%ebp
80482f7: 83 ec 08 sub $0x8,%esp
80482fa: 83 e4 f0 and $0xfffffff0,%esp
80482fd: b8 00 00 00 00 mov $0x0,%eax
8048302: 29 c4 sub %eax,%esp
8048304: b8 2b 00 00 00 mov $0x2b,%eax
8048309: c9 leave
804830a: c3 ret
804830b: 90 nop

//exit.o – main
08048324 :
8048324: 55 push %ebp
8048325: 89 e5 mov %esp,%ebp
8048327: 83 ec 08 sub $0x8,%esp
804832a: 83 e4 f0 and $0xfffffff0,%esp
804832d: b8 00 00 00 00 mov $0x0,%eax
8048332: 29 c4 sub %eax,%esp
8048334: 83 ec 0c sub $0xc,%esp
8048337: 6a 2b push $0x2b
8048339: e8 26 ff ff ff call 8048264
804833e: 90 nop
804833f: 90 nop

So there is some difference and looking closely it is that in case of ‘exit’
and explicit ‘call’ is made using call instruction (and hence pushing of
arguments to the stack) while this overhead is avoided in case of a return.

Ok. so that was a short dip in the code for two empty programs – result of a free mind.

how to enforce the instantiation of objects on heap ?

A nice question, I came through while being in an interview. Well, so how do you make sure that the object can be instantiated only on heap and not on stack ? so, if you are of the kind who don’t think without being given the use and purpose .. well the purpose is that your class may be a heavy one so storing objects on stack may be a killer.

Answer popped up my mind quite easily. Let’s suppose we have a class A,

class A {
int a[10000];
public:
A();
void print_arr();
}

Use the C++ access specifiers and make the constructor itself private. Now there is no way to instantiate the class. Pretty useless.

class A {
int a[10000];
A();
public:
void print_arr();
}

Now let’s make it useful by adding a factory function (or method) to it. This will act as the only way to instantiate an object. As with any factory method, it has to be static to be actually useful. Otherwise its as dumb a class as the one above.

class A {
int a[10000];
A();
public:
static A* getAnObject() { return new A(); }
void print_arr();
}

well that was it. problem solved. I am such a happy go lucky. But my interviewer friend had yet another idea (probably) in his mind and he asked me for some other way.

I am still puzzled.. some one there for help ?