Return reference from assignment

Started by
8 comments, last by King Mir 10 years, 10 months ago

How can I assign a value to a variable and return a pointer to the variable that was assigned to within the same expression in C99?

This is how it is done in 2 statements but nesting will make it look like pseudo assembler because I need garbage collection for lists:


{
int T;
T = 5 + 5;
Method(&T);
}
Advertisement
In C++ you can do
int T;
Method(&(T = 5 + 5));
but I don't think that is possible in C.

In C++ you can do


int T;
Method(&(T = 5 + 5));
but I don't think that is possible in C.

That is good to know if I decide to switch to a C++ backend to support more libraries.

You could use , operator, e.g.:

#include <stdio.h>

void fun(int *x)
{
        printf("%d\n", *x);
}

int main(void)
{
        int i = 0;
        fun( (i = 5, &i) );
}
Cheers,
hs.

You could use , operator, e.g.:


#include <stdio.h>

void fun(int *x)
{
        printf("%d\n", *x);
}

int main(void)
{
        int i = 0;
        fun( (i = 5, &i) );
}
Cheers,
hs.

That works great. :)

I don't understand your requirement for mushing all this into a single statement. That code is extremely confusing. There is probably a cleaner way to write this, perhaps something like:

#include <stdio.h>
 
void fun(int *x)
{
    printf("%d\n", *x);
}
 
void fun_with(int *pointer, int value)
{
    *pointer = value;
    fun(pointer);
}
 
int main(void)
{
    int i = 0;
    fun_with(&i, 5);
}

Your reference to "garbage collection" is unclear to me too.

I don't understand your requirement for mushing all this into a single statement. That code is extremely confusing. There is probably a cleaner way to write this, perhaps something like:


#include <stdio.h>
 
void fun(int *x)
{
    printf("%d\n", *x);
}
 
void fun_with(int *pointer, int value)
{
    *pointer = value;
    fun(pointer);
}
 
int main(void)
{
    int i = 0;
    fun_with(&i, 5);
}

Your reference to "garbage collection" is unclear to me too.

I am making a compiler for a high level language that cross compile to C99 and it's own virtual assembler code.

The assignment is just a way to store the value so that the end of the statement can clean it up after concatunating a list and not storing the result.

If I write it separated then I can't use dangling else for "else if" and have to make a nested "if".

I'm afraid I don't really understand you, but I guess if the code is being automatically generated then the stylistic issues are perhaps less important.

Yes, forgot to add a disclamer - I totally agree that it's unreadable. "," is rarely used for executing statements in sequence.
And using it in a function call makes things even more confusing.

Cheers,
hs.

You might instead do:

int main(void)
{
    int i = 0;
    i = 5 , fun(&i);
}

I think it's clearer.

This topic is closed to new replies.

Advertisement