Quick actions

cmd+k|ctrl+k

Navigation

Languages

ToString

Snippet info

Language

Cpp

Visibility

public

Author

evine

Created

2016-05-05T10:20:33Z

Updated

2016-05-06T12:43:49Z

#include <stdio.h>
#include <stdlib.h>
#include "foldl.h"


#define StringLength(...) FOLD(StringLength_, __VA_ARGS__)
int StringLength_(int i, double a)
{
    return snprintf(0,0,"%g",a) + i;
}
int StringLength_(int i, char *a)
{
    return snprintf(0,0,a) + i;
}

#define StringWrite(...) FOLD(StringWrite_, __VA_ARGS__)
char *StringWrite_(char *Buffer, double a)
{
    Buffer += snprintf(Buffer,0xFFFFFFFFFFFFFFFF,"%g",a);
    return Buffer;
}
char *StringWrite_(char *Buffer, char *a)
{
    Buffer += snprintf(Buffer,0xFFFFFFFFFFFFFFFF,a);
    return Buffer;
}

#define ToString(...) \
(StringWrite((char *)alloca(StringLength(0, __VA_ARGS__) + 1), __VA_ARGS__) \
- StringLength(0, __VA_ARGS__))

/*
How this works:
StringLength(0, __VA_ARGS__)
This will accumulate the required length of the string.
alloca(StringLength)
Allocate space for the string on the stack. And return the 
pointer to:
StringWrite(pointer, __VA_ARGS__)
StringWrite writes to the buffer and moves the pointer
forward in the buffer.
And finally we have a bogus pointer that points to the end so
we subtract the length again.
StringWrite() - StringLength();

If we're lucky the compiler realizes there are two identical calls
to StringLength so it optimizes that away.

Yes, I've only overloaded "char *" and "double", as this is only
a sample on how you could do it.
*/


int main()
{
    double SomeNumber = 5.3;
    char *SomeString = ToString(SomeNumber);
    printf(SomeString);
    printf("\n");
    
    char *OtherString = ToString(1.2, " and ", SomeNumber, "\n");
    printf(OtherString);
    
    printf(ToString(1," er fint\n"));
    
    return 0;
}










INFO