ridthyself
ridthyself

Reputation: 839

unexpected output from a function returning a string

I have a function stuff() which returns a string to be printed from main.

#include <stdio.h>

char* stuff(char* thing) {
        return ("this and %s", thing);
}

int main() {
        char* thing = "that";
        printf("%s\n", stuff(thing));
        return 0;
}       

I'm expecting

this and that

to be printed when the program is run, but instead I see:

that

Is someone able to walk me through what the program is actually doing, and more importantly, what I'm doing wrong?

Upvotes: 3

Views: 74

Answers (2)

shuttle87
shuttle87

Reputation: 15934

pbq2's answer explains very well why you get the expected output you get due to the comma operator. So I'd like to address your expectations, it looks like you are expecting some sort of string formatting expression to occur like you would see in other languages such as python. Unfortunately no such behavior happens in C. You need to use something like snprintf to do what you want here.

#include <stdio.h>

char* stuff(const char* thing) {
    char* ret = malloc(100);//make sure you deallocate this later!
    snprintf(ret, 100, "this and %s", thing);
    return ret;
}

int main() {
    const char* thing = "that";
    printf("%s\n", stuff(thing));
    return 0;
}

Also you might note that I have changed the original code to use const char* instead. This is because string literals should not be modified.

Upvotes: 2

pb2q
pb2q

Reputation: 59617

You're using an expression with the comma operator as the return value of your function.

The comma operator evaluates both operands (the expressions on either side of the comma), and the result of the expression is the result of evaluating the second expression: the expression on the right hand side of the comma. in your case, the second expression is the result, and hence is returned as the return value of your function.

So the result of the return statement in your function is equivalent to:

return thing;

Which is why the result of your function is the string "that".

You seem to be expecting some kind of printf style string formatting from this expression:

("this and %s", thing);

but it won't work like this: it's just an expression using the comma operator.

In C, concatenating strings isn't this easy. Look into the standard string strcat family of functions (see documentation for strncat here), or one of the sprintf family of functions (documentation for snprintf here).

Upvotes: 8

Related Questions