← Back to context

Comment by eulgro

19 days ago

To be honest, these all seem like pretty basic features.

Goto is easier to implement than an if statement. Postincrement behaves no differently in a switch statement than elsewhere.

Yes, you are right that a post-increment in a switch statement is no differently than elsewhere. The goal I had set was to implement a small easy to read C compiler. For that reason I tried to implement it as a single pass compiler that would generate code on the fly. The target was a small stack based language, which did support variable scoping and gotos, but not a switch. My first attempt was to implement the switch statement with chained if-statements where the switch expression would be evaluate over and over again. This only works if the switch expression did not have side effects and that the 'default' case would always come at the end. But that did not work, so I had to come up with another solution, a solution that would only evaluate the switch expression once. I decided to store the value on the stack and duplicate the value whenever needed for comparison. But that would require the value to be popped once a case was selected. A goto jumping from one case to another should land after the location where the value is popped, otherwise it would corrupt the stack. I fear that this solution does not work correctly when a case occurs within a for, while, do-loop, or if-statement. cases may occur everywhere in the enclosed code. This is sometimes used to emulate co-routines or generator functions.

Did you know that C has a keyword that is only a keyword in some places and that there is a function that can have two or three parameters?

  • Maybe the strategy from TCC itself is useful here: emit case bodies as a giant block first then jump back with cascaded if's at end. https://godbolt.org/z/TdE11jjxb

    > Did you know that C has a keyword that is only a keyword in some places and that there is a function that can have two or three parameters?

    What are those? Please tell!

    • A good idea that I had not thought about.

      defined is a pre-processor 'keyword' that only is used in conditions after #if and #elif. Elsewhere it is ignored by the pre-processor. You could argue that it is not a real keyword. But lets see what happens when you define it as a define with: '#define defined 1'.

      The function main can be defined with two or three parameters. The third contains the environment. You can also get the environment with 'argv + (argc + 1)'.