Saturday, October 8, 2011

Output of C program (printf)

What would be the output of the following C program? (Is it a valid C program?)
#include <stdio.h>
int main()
{
int i=43;
printf("%d\n",printf("%d",printf("%d",i)));
return 0;
}

Output : 4321

Explanation:This will produce output “4321”. The return type of printf is “int” which is the number of characters written to stdout.
printf("%d\n",printf("%d",printf("%d",i)));
printf("%d\n",printf("%d",printf("%d",43))); => 43
printf("%d\n",printf("%d",2)); => 2
printf("%d\n",1); => 1


Sunday, September 25, 2011

To find the length of string litteral or char array, We can use sizeof than strlen

sizeof is evaluated by the compiler where as strlen is evaluated at runtime.
Examples 1. int len = sizeof(“akamai”) - 1;

2. Char a[] = “akamai”; int len = sizeof(a) - 1;

3. Char *a = “akamai”; don’t use sizeof, please use strlen(a);

Thursday, October 21, 2010

Static C strings

1)
main()
{
char a[4]="HELLO";
printf("%s",a);
}
Answer:
Compiler error: Too many initializers
Explanation:
The array a is of size 4 but the string constant requires 6 bytes to get
stored.
174)
 main()
{
char a[4]="HELL";
printf("%s",a);
}
Answer:
HELL%@!~@!@???@~~!
Explanation:
The character array has the memory just enough to hold the string
“HELL” and doesnt have enough space to store the terminating null
character. So it prints the HELL correctly and continues to print garbage
values till it accidentally comes across a NULL character.

Friendship isn't inherited, transitive, or reciprocal

Just because I grant you friendship access to me doesn't automatically grant your kids access to me, doesn't automatically grant your friends access to me, and doesn't automatically grant me access to you.
  • I don't necessarily trust the kids of my friends. The privileges of friendship aren't inherited. Derived classes of a friend aren't necessarily friends. If class Fred declares that class Base is a friend, classes derived from Base don't have any automatic special access rights to Fred objects.
  • I don't necessarily trust the friends of my friends. The privileges of friendship aren't transitive. A friend of a friend isn't necessarily a friend. If class Fred declares class Wilma as a friend, and class Wilma declares class Betty as a friend, class Betty doesn't necessarily have any special access rights to Fred objects.
  • You don't necessarily trust me simply because I declare you my friend. The privileges of friendship aren't reciprocal. If class Fred declares that class Wilma is a friend, Wilma objects have special access to Fred objects but Fred objects do not automatically have special access to Wilma objects.

Should I design my classes from the outside (interfaces first) or from the inside (data first)?

First think about what the object logically represents, not how you intend to physically build it. For example, suppose you have a Stack class that will be built by containing a LinkedList:
 class Stack {
 public:
   
...
 private:
   LinkedList list_;
 };
Should the Stack have a get() method that returns the LinkedList? Or a set() method that takes a LinkedList? Or a constructor that takes a LinkedList? Obviously the answer is No, since you should design your interfaces from the outside-in. I.e., users of Stack objects don't care about LinkedLists; they care about pushing and popping.
Now for another example that is a bit more subtle. Suppose class LinkedList is built using a linked list of Node objects, where each Node object has a pointer to the next Node:
 class Node { /*...*/ };

 class LinkedList {
 public:
   
...
 private:
   Node* first_;
 };
Should the LinkedList class have a get() method that will let users access the first Node? Should the Node object have a get() method that will let users follow that Node to the next Node in the chain? In other words, what should a LinkedList look like from the outside? Is a LinkedList really a chain of Node objects? Or is that just an implementation detail? And if it is just an implementation detail, how will the LinkedList let users access each of the elements in the LinkedList one at a time?
The key insight is the realization that a LinkedList is not a chain of Nodes. That may be how it is built, but that is not what it is. What it is is a sequence of elements. Therefore the LinkedList abstraction should provide a LinkedListIterator class as well, and that LinkedListIterator might have an operator++ to go to the next element, and it might have a get()/set() pair to access its value stored in the Node (the value in the Node element is solely the responsibility of the LinkedList user, which is why there is a get()/set() pair that allows the user to freely manipulate that value).
Starting from the user's perspective, we might want our LinkedList class to support operations that look similar to accessing an array using pointer arithmetic:
 void userCode(LinkedList& a)
 {
   for (LinkedListIterator p = a.begin(); p != a.end(); ++p)
     std::cout << *p << '\n';
 }
To implement this interface, LinkedList will need a begin() method and an end() method. These return a LinkedListIterator object. The LinkedListIterator will need a method to go forward, ++p; a method to access the current element, *p; and a comparison operator, p != a.end().
The code follows. The important thing to notice is that LinkedList does not have any methods that let users access Nodes. Nodes are an implementation technique that is completely buried. This makes the LinkedList class safer (no chance a user will mess up the invariants and linkages between the various nodes), easier to use (users don't need to expend extra effort keeping the node-count equal to the actual number of nodes, or any other infrastructure stuff), and more flexible (by changing a single typedef, users could change their code from using LinkedList to some other list-like class and the bulk of their code would compile cleanly and hopefully with improved performance characteristics).
 #include <cassert>    // Poor man's exception handling

 class LinkedListIterator;
 class LinkedList;

 class Node {
   
// No public members; this is a "private class"
   friend class LinkedListIterator;   
// A friend class
   friend class LinkedList;
   Node* next_;
   int elem_;
 };

 class LinkedListIterator {
 public:
   bool operator== (LinkedListIterator i) const;
   bool operator!= (LinkedListIterator i) const;
   void operator++ ();   
// Go to the next element
   int& operator*  ();   
// Access the current element
 private:
   LinkedListIterator(Node* p);
   Node* p_;
   friend class LinkedList;  
// so LinkedList can construct a LinkedListIterator
 };

 class LinkedList {
 public:
   void append(int elem);    
// Adds elem after the end
   void prepend(int elem);   
// Adds elem before the beginning
   
...
   LinkedListIterator begin();
   LinkedListIterator end();
   
...
 private:
   Node* first_;
 };
Here are the methods that are obviously inlinable (probably in the same header file):
 inline bool LinkedListIterator::operator== (LinkedListIterator i) const
 {
   return p_ == i.p_;
 }

 inline bool LinkedListIterator::operator!= (LinkedListIterator i) const
 {
   return p_ != i.p_;
 }

 inline void LinkedListIterator::operator++()
 {
   assert(p_ != NULL);  
// or if (p_==NULL) throw ...
   p_ = p_->next_;
 }

 inline int& LinkedListIterator::operator*()
 {
   assert(p_ != NULL);  
// or if (p_==NULL) throw ...
   return p_->elem_;
 }

 inline LinkedListIterator::LinkedListIterator(Node* p)
   : p_(p)
 { }

 inline LinkedListIterator LinkedList::begin()
 {
   return first_;
 }

 inline LinkedListIterator LinkedList::end()
 {
   return NULL;
 }
Conclusion: The linked list had two different kinds of data. The values of the elements stored in the linked list are the responsibility of the user of the linked list (and only the user; the linked list itself makes no attempt to prohibit users from changing the third element to 5), and the linked list's infrastructure data (next pointers, etc.), whose values are the responsibility of the linked list (and only the linked list; e.g., the linked list does not let users change (or even look at!) the various next pointers).
Thus the only get()/set() methods were to get and set the elements of the linked list, but not the infrastructure of the linked list. Since the linked list hides the infrastructure pointers/etc., it is able to make very strong promises regarding that infrastructure (e.g., if it were a doubly linked list, it might guarantee that every forward pointer was matched by a backwards pointer from the next Node).
So, we see here an example of where the values of some of a class's data is the responsibility of users (in which case the class needs to have get()/set() methods for that data) but the data that the class wants to control does not necessarily have get()/set() methods.
Note: the purpose of this example is not to show you how to write a linked-list class. In fact you should not "roll your own" linked-list class since you should use one of the "container classes" provided with your compiler. Ideally you'll use one of the standard container classes such as the std::list<T> template.

() vs [] for subscripting in case of more than 1 parameter

Use operator() rather than operator[].
When you have multiple subscripts, the cleanest way to do it is with operator() rather than with operator[]. The reason is that operator[] always takes exactly one parameter, but operator() can take any number of parameters (in the case of a rectangular matrix, two parameters are needed).
For example:
 class Matrix {
 public:
   Matrix(unsigned rows, unsigned cols);
   double& operator() (unsigned row, unsigned col);        
 subscript operators often come in pairs
   double  operator() (unsigned row, unsigned col) const;  
 subscript operators often come in pairs
   
...
  ~Matrix();                              
// Destructor
   Matrix(Matrix const& m);               
// Copy constructor
   Matrix& operator= (Matrix const& m);   
// Assignment operator
   
...
 private:
   unsigned rows_, cols_;
   double* data_;
 };

 inline
 Matrix::Matrix(unsigned rows, unsigned cols)
   : rows_ (rows)
   , cols_ (cols)
   
//data_ <--initialized below (after the 'if/throw' statement)
 {
   if (rows == 0 || cols == 0)
     throw BadIndex("Matrix constructor has 0 size");
   data_ = new double[rows * cols];
 }

 inline
 Matrix::~Matrix()
 {
   delete[] data_;
 }

 inline
 double& Matrix::operator() (unsigned row, unsigned col)
 {
   if (row >= rows_ || col >= cols_)
     throw BadIndex("Matrix subscript out of bounds");
   return data_[cols_*row + col];
 }

 inline
 double Matrix::operator() (unsigned row, unsigned col) const
 {
   if (row >= rows_ || col >= cols_)
     throw BadIndex("const Matrix subscript out of bounds");
   return data_[cols_*row + col];
 }
Then you can access an element of Matrix m using m(i,j) rather than m[i][j]:
 int main()
 {
   Matrix m(10,10);
   m(5,8) = 106.15;
   std::cout << m(5,8);
   
...
 }

Matrix class is not array of arrays

The same reasons you encapsulate your data structures, and the same reason you check parameters to make sure they are valid.
A few people use [][] despite its limitations, arguing that [][] is better because it is faster or because it uses C-syntax. The problem with the "it's faster" argument is that it's not — at least not on the latest version of two of the world's best known C++ compilers. The problem with the "uses C-syntax" argument is that C++ is not C. Plus, oh yea, the C-syntax makes it harder to change the data structure and harder to check parameter values.
The point of the previous two FAQs is that m(i,j) gives you a clean, simple way to check all the parameters and to hide (and therefore, if you want to, change) the internal data structure. The world already has way too many exposed data structures and way too many out-of-bounds parameters, and those cost way too much money and cause way too many delays and way too many defects.
Now everybody knows that you are different. You are clairvoiant with perfect knowledge of the future, and you know that no one will ever find any benefit from changing your matrix's internal data structure. Plus you are a good programmer, unlike those slobs out there that occasionally pass wrong parameters, so you don't need to worry about pesky little things like parameter checking. But even though you don't need to worry about maintenance costs (no one ever needs to change your code), there might be one or two other programmers who aren't quite perfect yet. For them, maintenance costs are high, defects are real, and requirements change. Believe it or not, every once in a while they need to (better sit down) change their code.
Okay, my thongue wath in my theek. But there was a point. The point was that encapsulation and parameter-checking are not crutches for the weak. It's smart to use techniques that make encapsulation and/or parameter checking easy. The m(i,j) syntax is one of those techniques.
Having said all that, if you find yourself maintaining a billion-line app where the original team used m[i][j], or even if you are writing a brand new app and you just plain want to use m[i][j], you can still encapsulate the data structure and/or check all your parameters. It's not even that hard. However it does require a level of sophistication that, like it or not, the average C++ programmers fears. Fortunately you are not average, so read on.
If you merely want to check parameters, just make sure the outer operator[] returns an object rather than a raw array, then that object's operator[] can check its parameter in the usual way. Beware that this can slow down your program. In particular, if these inner array-like objects end up allocating their own block of memory for their row of the matrix, the performance overhead for creating / destroying your matrix objects can grow dramatically. The theoretical cost is still O(rows*cols), but in practice, the overhead of the memory allocator (new or malloc) can be much larger than anything else, and that overhead can swamp the other costs. For instance, on two of the world's best known C++ compilers, the separate-allocation-per-row technique was 10x slower than the than one-allocation-for-the-entire-matrix technique. 10% is one thing, 10x is another.
If you want to check the parameters without the above overhead and/or if you want to encapsulate (and possibly change) the matrix's internal data structure, follow these steps:
  1. Add operator()(unsigned row, unsigned col) to the Matrix class.
  2. Create nested class Matrix::Row. It should have a ctor with parameters (Matrix& matrix, unsigned row), and it should store those two values in its this object.
  3. Change Matrix::operator[](unsigned row) so it returns an object of class Matrix::Row, e.g., { return Row(*this,row); }.
  4. Class Matrix::Row then defines its own operator[](unsigned col) which turns around and calls, you guessed it, Matrix::operator()(unsigned row, unsigned col). If the Matrix::Row data members are called Matrix& matrix_ and unsigned row_, the code for Matrix::Row::operator[](unsigned col) will be { return matrix_(row_, col); }
Next you will enable const overloading by repeating the above steps. You will create the const version of the various methods, and you will create a new nested class, probably called Matrix::ConstRow. Don't forget to use Matrix const& instead of Matrix&.
Final step: find the joker who failed to read the previous FAQ and thonk him in the noggin.
If you have a decent compiler and if you judiciously use inlining, the compiler should optimize away the temporary objects. In other words, the operator[]-approach above will hopefully not be slower than what it would have been if you had directly called Matrix::operator()(unsigned row, unsigned col) in the first place. Of course you could have made your life simpler and avoided most of the above work by directly calling Matrix::operator()(unsigned row, unsigned col) in the first place. So you might as well directly call Matrix::operator()(unsigned row, unsigned col) in the first place.