compiler
compiler

Reputation: 4371

How do I interpret (assert) here in c?

void (assert)(int e)
{
    assert(e);
}

How does it work here?

Upvotes: 2

Views: 104

Answers (3)

Lindydancer
Lindydancer

Reputation: 26164

Since assert already is defined as a function-style macro, without the parentheses it would have been expanded both in the function header and in the body.

For example:

#define twice(x) ((x)+(x))
void twice(int i)
{
  return twice(i);
}

Will expand to the following, which clearly is not legal

void ((int i)+(int i))
{
  return ((i)+(i));
}

On the other hand:

#define twice(x) ((x)+(x))
void (twice)(int i)
{
  return twice(i);
}

Will expand to:

void (twice)(int i)
{
  return ((i)+(i));
}

The extra parentheses around the function name is simply ignored by the compiler.

This is a common trick often used in the source of the standard library, on in other contexts where there might be functions and macros with the same name.

Upvotes: 2

Prasoon Saurav
Prasoon Saurav

Reputation: 92942

void (assert)(int e) is equivalent to void assert(int)

Why would you need it?

Consider the following example

#include<stdio.h>
void foo(int a)
{
printf("%d", a);
}
#define foo(a) {/*I do nothing*/}

int main()
{
  foo(5); // won't call `foo`
}

How would you make sure when you call foo, its the function that is called and not the macro-definition substituted at the place of call?

The solution is to put an extra parenthesis like (foo)(5)

Similarly assert is already known to be a macro. That's the reason I can think of.

Upvotes: 3

geekosaur
geekosaur

Reputation: 61467

It's legal syntax, just writing it with extra parentheses. The reason you'd do that is because assert() is often defined as a macro; so the above function exists to make assert() be a real function, probably so you can set a breakpoint in it.

Upvotes: 1

Related Questions