4

code snippet code following:

#include <stdio.h>
#include <stdbool.h>

int test()
{
    return (printf("it is test\n"), false);
}

int main()
{ 
    if (false == test())
        printf("return result is false\n");
}

The return statement works but I don't know why it can work as i didn't encounter the statement before. Can any body help to explain the usage of return statement in this snippet code?

hellow
  • 12,430
  • 7
  • 56
  • 79
michael_J
  • 133
  • 1
  • 3
  • This is a `C` question and therefore there is no operator overloading. – hellow Nov 05 '18 at 08:50
  • @Blaze: That's half an answer. You first need to establish it's parsed as an operator. – MSalters Nov 05 '18 at 08:51
  • [Can 'return' return multiple values in C?](https://stackoverflow.com/q/3626648/995714), [How does this return statement with multiple values (variables) works?](https://stackoverflow.com/q/31810832/995714), [Function returning two things seperated by a comma in C](https://stackoverflow.com/q/24712884/995714), [Can a function return more than one value in C?](https://stackoverflow.com/q/27328544/995714) – phuclv Nov 05 '18 at 08:54
  • there is something called the comma operator: https://stackoverflow.com/questions/1737634/c-comma-operator – perreal Nov 05 '18 at 08:56
  • Note that `return` is a statement not a function call. Putting parentheses after it only affects precedence, nothing else. – cdarke Nov 05 '18 at 09:33

1 Answers1

3

To answer the actual main question, exactly one, If you wish to return more you need to pass in a pointer, or return one to a struct, ie:

#include <stdio.h>
#include <stdbool.h>

bool test(int * data)
{
    *data = printf("it is test\n");
    return false;
}

int main()
{
    int data;
    if (false == test(&data))
        printf("return result is false, data = %d\n", data);
}

As for why it works, please see: Comma-Separated return arguments in C function

Geoffrey
  • 10,843
  • 3
  • 33
  • 46
  • 2
    @hellow The actual question in the title asks exactly how many parameters `return` can take, this answer is correct as even with the comma operator, it still only takes one, the right most. – Geoffrey Nov 05 '18 at 08:58
  • Please note that structs are values too, so you really don't *need* to use pointers. – unwind Nov 05 '18 at 09:55