I have a question :
char *c[] = {"GeksQuiz", "MCQ", "TEST", "QUIZ"};
char **cp[] = {c+3, c+2, c+1, c};
char ***cpp = cp;
int main()
{
printf("%s ", *--*++cpp+3);
}
I am not able to understand the output = sQUIZ ,
my approach: first it will point to cpp+3 i.e c now ++c means pointing to "MCQ" , * of that would give the value "MCQ" ,can't understand what the -- before * would do here . or is my approach totally wrong ?
I will post it as an answer as was mentioned in comments. You should read at first this: http://en.wikipedia.org/wiki/Sequence_point also look here and you can search for dozens of articles accross the Internet about sequence points
. This stuff is as BAD as undefined behaviour
and unspecified behaviour
. You can read this post, especially the part What is the relation between Undefined Behaviour and Sequence Points?
in the accepted answer.
Probably this interview question implied your knowledge about sequence points then it is not as bas as I see it, but nevertheless NEVER EVER
write such a code even for your pet projects and I don't even want to mention production code. This is silly.
If they look for experienced C++/C developer they shouldn't ask such questions at all.
EDIT
Just for the tip about sequence points, because I saw some misunderstandings in other posted answer and in the comments. This is *--*++cpp+3
not an unspecified behaviour
or undefined behaviour
(I mean it is a bad code in general), but this IS:
int i =1;
*--*++cpp+i+i++;
The code above is unsequenced
and unspecified
. Please read about differences between undefined behaviour
, unspecified behaviour
, implementation-defined behavior
and sequence points
e.g. here .I wrote all this in order to explain you why you should avoid such a terrible code at all (whether it legal from the point of language standard or not). Yes, your code is legal, but unreadable, and, as you see in my edits, small changes made it illegal
. Do not think we don't want to help you, I mean the code similar to your is a bad code in general wherever it will be asked. It will be better if they asked you to explain WHY
such a code is bad and fragile - then it will be a good interview question.
P.S. The actual output is an empty string, because you print a null-terminator. See an excellent answer below - it explained the output from the point of C operators preceding (you should also learn it then such questions will not bother you at all).
All variables in this expression are modified only once. Maybe I don't understand something about sequence points, but I don't have no idea why people call this expression undefined behavior.
char *c[] = {"GeksQuiz", "MCQ", "TEST", "QUIZ"};
char **cp[] = {c+3, c+2, c+1, c};
char ***cpp = cp;
/*1*/ cpp; // == &cp[0]
/*2*/ ++cpp; // == &cp[1] (`cpp` changed)
/*3*/ *++cpp; // == cp[1] == c+2
/*4*/ --*++cpp; // == c+2-1 == &c[1] (`cp[1]` changed)
/*5*/ *--*++cpp; // == "MCQ"
/*6*/ *--*++cpp+3; // == "MCQ"+4 - it's pointer to '\0'
So it should not print anything.