• Source
    1. #include <stdio.h>
    2.  
    3. /* Search a string for matching parentheses. If the parentheses match, returns a
    4.  * pointer that addresses the nul terminator at the end of the string. If they
    5.  * don't match, the pointer addresses the first character that doesn't match.
    6.  */
    7. const char *match(const char *str)
    8. {
    9. if( *str == '\0' || *str == ')' ) { return str; }
    10. if( *str == '(' )
    11. {
    12. const char *closer = match(++str);
    13. if( *closer == ')' )
    14. {
    15. return match(++closer);
    16. }
    17. return str - 1;
    18. }
    19.  
    20. return match(++str);
    21. }
    22.  
    23.  
    24. int main(void)
    25. {
    26. int index;
    27. const char *test[] = {
    28. "())(", ")(", "))(", "(()"
    29. };
    30.  
    31. for( index = 0; index < sizeof(test) / sizeof(test[0]); ++index ) {
    32. const char *result = match(test[index]);
    33.  
    34. printf("%s:\t", test[index]);
    35. *result == '\0' ? printf("Good!\n") :
    36. printf("Bad @ char %zu\n", result - test[index] + 1);
    37. }
    38. }
    39.