Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function call followed by a comma separator [duplicate]

I was reading some material about errors that should be avoided when writing C programs and I came across the following code:

#include <stdio.h>

void foo(int param)
{
  printf("foo is called\n");
  printf("%d\n",param);
}

int main()
{
  return foo,(1);
}

The code above build without errors and warnings (it only show a warning when -Wall is activated) but when I run the small program nothing is displayed. The function foo is not called because of the comma separator.

My question is why the C standard allow such syntax? Shouldn't the compiler issue an error in this case? In which context this syntax could be used in some real use case?

Thanks in advance,

PD: I'm using GCC 4.8.3

EDIT:

Couldn't the compiler in this case detect the situation and issue an error instead of warning (as I said it only appears when -Wall is enabled)

like image 896
rkachach Avatar asked Dec 04 '22 02:12

rkachach


2 Answers

C is a simple, minimalist language where the programmer is supposed to know what they're doing.

In C, types convert to each other quite easily and the original C didn't even have function declarations -- the programmer was supposed to know how to call each function and with what parameters.

C was the programming language for Unix and

"UNIX was not designed to stop you from doing stupid things, because that would also stop you from doing clever things."—Doug Gwyn (https://en.wikiquote.org/wiki/Unix)

As a bonus, if the compiler doesn't try to be smart, compilation can be very fast.

C++ takes a very different approach to this.

As for practical applications of the , operator, take a look at: https://en.wikipedia.org/wiki/Comma_operator

The comma operator has relatively limited use cases. Because it discards its first operand, it is generally only useful where the first operand has desirable side effects. Further, because it is rarely used outside of specific idioms, and easily mistaken with other commas or the semicolon, it is potentially confusing and error-prone. Nevertheless, there are certain circumstances where it is commonly used, notably in for loops and in SFINAE (http://en.cppreference.com/w/cpp/language/sfinae). For embedded systems which may have limited debugging capabilities, the comma operator can be used in combination with a macro to seamlessly override a function call, to insert code just before the function call.

like image 136
PSkocik Avatar answered Jan 22 '23 05:01

PSkocik


return foo,(1);

is equivalent to:

foo; // Nothing happens. This does not call the function.
return (1);

Perhaps you meant to use:

foo(1);
return 1;
like image 27
R Sahu Avatar answered Jan 22 '23 06:01

R Sahu