Showing posts with label Programming Trivia. Show all posts
Showing posts with label Programming Trivia. Show all posts

Hello World!

Tuesday, August 31, 2010

It is a very commonplace question for technical interviews that tests your proficiency in C. The problem is quite well-known and so is its solution. The objective is to print two string literals say "Hello" and "World" using two printf statements where one printf should be a part of an if block and the other a part of its matching else. The most common solution is

if(!printf("Hello "))
{}
else printf("World");

Being aware that printf returns the number of characters printed on screen (in case of Hello, it is 5) which we negate using the logical operator ! to make the entire expression as 0 implying false and thus the else part is executed.

Now what if, you were restricted to use any of the logical operators for achieving the same job. Well, here's a solution. The most undermined comma (,) operator plays an interesting role in doing the job:

if(printf("Hello") , NULL) //we can even write 0 instead of NULL
{}
else printf("World");
Note in C, the comma operator has an interesting semantic. All expressions separated by comma's are evaluated from left-to-right however the value of the entire expression is the right-most expression. i.e a= (5+2,3+5,6*4); then a gets the value 24, though all the previous expressions are evaluted. Now using this feature, the if condition part is well explained.

If someone can come up with a more compact and cryptic solution to this, do post it here.

Read more...

"C" the intracacies

Sunday, May 30, 2010

The other day, one of my nerdy mates, Rajdeep had put forth this problem, which caught me on the back foot. Apparently, the problem appealed like a fundamental predict the output snippet, but the exact reasoning is yet to be found. Following is the code snippet with some steps, someone needs the explain the reason behind such a weird output.

//File name: googly.c
#include
int main()
{
int a,b;
a=((b=5)+1); //Line 2
printf("a=%d b=%d",a,b);
return 0;
}

As you would have expected Line 2 essentially reduces to two sequential statements, b=5 and then a=b+1 and you get the result 'a'=6 and 'b'=5;

Now try replacing Line 2 with the expression a=((b=5)++)and then try to compile using a standard C compiler and you would observe an compilation error. You might come across a logic to explain that error.

But the strange behavior doesn't end here, save the code with a .cpp extension, compile it with a standard C++ compiler & you'd be startled to note that the error is gone and the program runs seamlessly to produce the output as a='5' and b='6'.

I suppose there's some compilation issue that makes it happen, but need a succinct logical explanation to this. Your reasonings are awaited...

Read more...

  © Blogger templates Newspaper by Ourblogtemplates.com 2008

Back to TOP