On Monday, 20 December 2021 at 11:30:09 UTC, rumbu wrote:
On Monday, 20 December 2021 at 10:49:20 UTC, rempas wrote:
On Monday, 20 December 2021 at 09:30:30 UTC, rumbu wrote:

Thanks a lot for the info. When I try to use this code, I'm getting the following error:

```
Error: expression expected, not `%`
Error: expression expected, not `%`
```

My fault, I forgot to put some char delimiters. You can find tested code here:

https://run.dlang.io/is/KfdED0

So I suppose there is a problem with string concatenation. I couldn't use it anyway because it is inefficient and because I'm using betterC. Do you know any other way that I can concatenate strings that does not depend an the Garbage Collector or the standard library?

Enums (that's why the string is declarated as enum) are evaluated at compile time, the concatenation op will not end in your code as instruction, so you can do anything outside betterC rules as long you do it at compile time. You are just building some code to use later, the compiler does not generate any instruction for it.

In the example above you can press the AST button to see exactly how your code is generated.

Wnen you have doubts about a generated string you can always test it with ```pragma msg```. In this case, if you write:

```
pragma(msg, add_char!'%');
```

you will have in the output exactly what the compiler will generate for your mixin.

Ehh, it still fails; should've explicitly put the length of the array and the `extern (C)` in `main`

```d
module demo;

//i am just declaring these to have them.
size_t stdout_index;
enum STDOUT_BUF_LEN = 42;
char[STDOUT_BUF_LEN] stdout_buffer; /+indexing an uninitialized dynamic array resulted in out of bounds error even for index == 0+/
alias i32 = int;
void sys_write(int i, void* p, int index) {}
//


enum add_char(char c) =

  `if (stdout_index < STDOUT_BUF_LEN) {
    stdout_buffer[stdout_index++] ='` ~ c ~ `';
    continue;
  } else {
    sys_write(1, stdout_buffer.ptr, cast(i32)stdout_index);
    stdout_index = 0;
    stdout_buffer[stdout_index++] ='` ~ c ~ `';
    continue;
  }`;

extern(C) /+added this because you used -betterC+/ void main()
{

    while (true) {
                mixin(add_char!'%');
                mixin(add_char!'$');
    }



}
```

Reply via email to