Kevin
Kevin

Reputation: 1151

Strange way to reverse a string with recursion

I found this code:

#include <stdio.h> 
#include <ctype.h> 

int f(int c) { 
    static int b;

    if (isspace(c))
        return b = c & '\n';

    f(getchar()); 

    return putchar(c) == b && f(c); 
} 

int main(void) { 
   return f(0); 
}

I want to understand how this code works, I never saw this type of code so elaborate, what is it for c & '\n' why this comparison putchar(c) == b?

Someone help me understand this?

Upvotes: 3

Views: 105

Answers (2)

Armali
Armali

Reputation: 19375

This is not a correct program; there is an infinite recursion if its input doesn't contain a character for which PeteB found b to become nonzero (\t \n \v \f \r) - try … </dev/null.

Upvotes: 0

PeteB
PeteB

Reputation: 372

c & '\n' is only called when isspace is true, the value calculated is stored in variable 'b' which is static so it will carry both forwards and backwards through the recursive stack as it expands and contracts.

I had to look isspace up and found: http://www.tutorialspoint.com/c_standard_library/c_function_isspace.htm which shows there are 6 characters matched by isspace.

The & is a bitwise AND, which will return a value with bits set only if the bits in both parameters are enabled (1).

Going through the values from isspace we get:

  • 0x20 (space) AND 0x0a (\n) gives 0 (\0) string terminator
  • 0x09 (tab) gives 0x08 (backspace)
  • 0x0a (newline) gives 0x0a (newline)
  • 0x0b (vertical tab) gives 0x0a again
  • 0x0c (feed) gives 0x08 again
  • 0x0d (carriage return) gives 0x08 again

Looking at this, I would say the desired result were probably the terminator for space and the newline for newline characters. I would guess that the other results were not desired or anticipated, and the tab to backspace conversion will probably cause the function to produce very strange output when tabs are in the input stream.

Overall this is a dumb way to design code and may be part of an entry for the obfuscated C competition where such things are applauded. Picking it apart in detail may teach you some very important things about the C language, but this is not something you should ever aim to use in production code.

Upvotes: 1

Related Questions