views:

194

answers:

5

I need to pass a string literal to a function

myfunction("arg1" DEF_CHAR "arg1");

now part of that constructed string literal needs to be a function return

stmp = createString();
myfunction("arg1" stmp "arg2"); //oh that doesn't work either

is there any way to do this in one line?

myfunction("arg1" createString() "arg2"); //what instead?

NOTE: C only please.

My goal is to avoid initializing a new char array for this =/

+1  A: 

You need to make a character array for this; only string literals are concatenated by the compiler.

jemfinch
+4  A: 

You cannot build string literal at runtime, but you can create the string, like this:

char param[BIG_ENOUGH];

strcpy(param, "arg1");
strcat(param, createString());
strcat(param, "arg2");
myfunction(param);
qrdl
In fact the reason that `strcpy()` and `strcat()` return a pointer to the destination string is for precisely this situation - it lets you do `myfunction(strcat(strcat(strcpy(param, "arg1"), createstring()), "arg2"))`
caf
@caf Thanks, didn't know that.
qrdl
A: 

Nope. No way to do this in pure C without allocating a new buffer to concatenate the strings.

Nick Meyer
+2  A: 
char buffer[1024] = {0};
//initialize buffer with 0 
//tweak length according to your needs

strcat(buffer, "arg1");
strcat(buffer, createString()); //string should be null ternimated
strcat(buffer, "arg2");

myfunction(buffer);
N 1.1
+2  A: 

C does not support dynamic strings, so what you're attempting is impossible. The return value from your createString() function is a variable, not a literal, so you can't concatenate it with other literals. That being said, if it's really important to you to have this on one line, you can create a helper function to facilitate this, something like the following:

char * my_formatter( const char * format, ... )
{
...
}

myfunction(my_formatter("arg1%sarg2", createString()));

There are some memory management and thread saftey issues with this approach, however.

Peter Ruderman