MyrionSC2
MyrionSC2

Reputation: 1318

using variable in initialization of same variable

I fell over this little thing while coding:

char* strinit(char* str) {
    str = (char*) malloc(100);
    strcpy(str, "hello SO");
    return str;
}
int main()
{
    char* str = strinit(str);
    return 0;
}

As you can see, I am using the same variable that I am declaring to initialize it. This is no problem. I tried the same thing in Java. That causes errors.

So my question is: Is there any problems doing this? Can I use it in my code in good conscience?

Upvotes: 2

Views: 80

Answers (2)

harper
harper

Reputation: 13690

Not everything you can do should be done. The code

char* strinit(char* str) {
    str = (char*) malloc(100);
    strcpy(str, "hello SO");
    return str;
}

uses a parameter only as a local variable. You should change it to

char* strinit(void) {
    char* str = malloc(100);
    strcpy(str, "hello SO");
    return str;
}

and call the function without parameters.

Edit: There is only a little problem with the actual call of your function. The value of the variable str in the main function is passed to the strinit function. This is cheap in your case. But this can be expensive if the parameter type is a more complex type. The compiler will create a copy of the parameter what can call the objects constructor. Of course, the copy of a pointer is cheap.

Upvotes: 1

houssam
houssam

Reputation: 1873

C & C++ consider that char* str = strinit(str); is legal; because it is evaluated to:

 char* str;
 str = strinit(str);

see Why is 'int i = i;' legal?

Upvotes: 1

Related Questions