Dan Bechard
Dan Bechard

Reputation: 5291

What is the purpose of the comma in this C macro?

I saw something similar to this in stretchy_buffer.h:

#define stb_sb_free(a) ((a) ? free(stb__sbraw(a)),0 : 0)

What is the purpose of the ,0 after the call to free()?

Similarly, there are two curious commas here:

#define stb_sb_add(a,n) (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])

It seems like it's running multiple statements, but wouldn't that require a semicolon?

Upvotes: 4

Views: 145

Answers (1)

masoud
masoud

Reputation: 56479

What happens in this line

#define stb_sb_free(a) ((a) ? free(stb__sbraw(a)),0 : 0)

is, if a corrsponseds to true, first free(stb__sbraw(a)) will be executed, then 0 will be returned due to ,0.

In general, all expressions which they're separated by comma will be evaluated, but the result has the type and value of the rightmost expression.

Upvotes: 5

Related Questions