Search code examples
cmisra

What is the syntax in c to combine statements as a parameter


I have an inkling there is an old nasty way to get a function run as a parameter is calculated, but sine I do not know what it is called I cannot search out the rules.

An example

char dstr[20];
printf("a dynamic string %s\n", (prep_dstr(dstr),dstr));

The idea is that the "()" will return the address dstr after having executed the prep_dstr function.

I know it is ugly and I could just do it on the line before - but it is complicated...

#

Ok - in answer to the pleading not to do it.

I am actually doing a MISRA cleanup on some existing code (not mine don't shoot me), currently the 'prep_dstr' function takes a buffer modifies it (without regard to the length of the buffer) and returns the pointer it was passed as a parameter.

I like to take a small step - test then another small step.

So - a slightly less nasty approach than returning a pointer with no clue about its persistence is to stop the function returning a pointer and use the comma operator (after making sure it does not romp off the end of the buffer).

That gets the MISRA error count down, when it all still works and the MISRA errors are gone I will try to get around to elegance - perhaps the year after next :).


Solution

  • Yes, the syntax you use will work for your purpose.

    However, please consider writing clean and readable code. For instance,

    char buffer[20];
    
    char *destination = prepare_destination_string(buffer);
    
    printf("a dynamic string %s\n", destination);
    

    Everything can be cleanly named & understood, and intended behaviour easy to infer. You could even omit certain parts if you so would, like destination, or perform easier error checking.