C Programming Puzzle #2


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

The code of the first puzzle was:

#include <stdio.h>

int main(){

    if("Hello World" == "Hello World"){
       printf("Yes ","No ");
    }

    printf(10+"Hello World"-4);

return 0;
}

The answer is that it prints “Yes World”. First of all the statement inside the IF will be executed because we compare the same pointer, which returns 1 (although in some machines this might not be true, because storing similar string literals only once is not required by the ANSI C standard). The first printf will only print “Yes”, though, because the function only takes one parameter in this case, so “No” is ignored. The second printf will only print “World” because the pointer to the initial character was incremented by 6 bytes.

And here’s the second puzzle. What does it print, if anything? (obviously trying to find it out without actually running the program!).

#include <stdio.h>

void foobar(char *str1, char *str2){
  while (*((str1++)+6) = *((str2++)+8));
}

int main(){
  char str1[] = "Hello World";
  char str2[] = "Foo Bar Bar"; 

  foobar(str1,str2);

  printf("%s %sn",str1, str2);

  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *