Amardeep reddy
Amardeep reddy

Reputation: 127

How to add curly braces to indented code?

I am trying to convert a pseudo-code to C code. The pseudo-code is indented like Python. I want to convert that into curly braces. Is there a way to do it ? Example the pseudo-code looks like this:

    int my_function(int a, int b)
        int c;
        int d;
        if(a==5)
            c = 6;
            d = 7;
        else
            c = 8;
            d = 9;
        return (c+d);

I want to convert it into the following.

    int my_function(int a, int b)
    {
        int c;
        int d;
        if(a==5)
        {
            c = 6;
            d = 7;
        }
        else
        {
            c = 8;
            d = 9;
        }
        return (c+d);
    }

Upvotes: 1

Views: 258

Answers (2)

chqrlie
chqrlie

Reputation: 144770

To turn this Python-like pseudo-code, you can insert a { before any line indented more than the current one and as many } after the block as there are indentation levels to unwind.

There are multiple styles as to where the braces belong. The example you posted in the question tends to increase the number of lines at the expense of readability and may make some silly mistakes harder to detect, such as this:

    while ((c = getchar()) = EOF);
    {
       putchar(c);
    }

A popular alternative style has the opening brace inserted at the end of the line that commands the block (the if, for, while, do or switch statement) and the closing brace at the beginning of a separate line, followed by the else part of the if statement or the while part of the do statement.

Here your code modified for this style:

int my_function(int a, int b) {
    int c, d;

    if (a == 5) {
        c = 6;
        d = 7;
    } else {
        c = 8;
        d = 9;
    }
    return c + d;
}

Upvotes: 1

Clifford
Clifford

Reputation: 93476

Assuming you are intending to write real code to perform the transformation, rather then looking for a tool or editor facility, then it is simply text processing.

In (true) pseudo-code, you would do the following:

For each line:

  if the indentation is greater than the current level then:
    insert a line before with an opening brace at the current level, 
    increase the current level

  otherwise if the indentation is less than the current level then:
    While current level > new level
      insert a line after with an closing brace at the current level, 
      decrease the current level

Upvotes: 2

Related Questions