Reputation: 1346
#include <stdio.h>
int main()
{
int a,b;
b=10;
a=b--;
printf("a=%d b=%d\n",a,b);
a=b--- //Here why i didn't get error....???
printf("a=%d b=%d\n",a,b);
//a=b---- or a=b---; //for these, i got error
a=b--;
printf("a=%d b=%d\n",a,b);
}
why statement b---
doesn't show error. Can i say this is a bug...? If no, please explain what's going on internally...?
Upvotes: 1
Views: 76
Reputation: 227418
printf
returns int
, so you have a syntactically valid statement*. This
a=b---
printf("a=%d b=%d\n",a,b);
is a single statement, which is exactly the same as this:
a = b-- - printf("a=%d b=%d\n",a,b);
or, for extra clarity,
a = (b--) - printf("a=%d b=%d\n", a, b);
In other words, for ints
x
and y
, x--- y
is parsed as (x--) - y
.
* While syntactically valid, the statement itself is undefined behaviour, since there is a modification and a read of b
without an intervening sequence point
Upvotes: 7
Reputation: 311038
Function printf
has return type int
.
From the C Standard
3 The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.
So this statement
a=b--- //Here why i didn't get error....???
printf("a=%d b=%d\n",a,b);
is a valid C statement. It can be rewritten for descriptive reason as
a = b-- - printf("a=%d b=%d\n",a,b);
or
int tmp = printf("a=%d b=%d\n",a,b);
a = b-- - tmp;
Take into account that the original statement has undefined behaviour because it is unspecified when the side effect of expression b-- will be applied to b. But in any case the code will be compiled.
Upvotes: 3
Reputation: 4753
a=b--- //Here why i didn't get error....???
printf("a=%d b=%d\n",a,b);
This is a single statement and is valid since it is being teminated by semicolon.
Printf returns integer , so integer-integer which is valid opertion
//a=b---- or a=b---; //for these, i got error
Here , the above staments are syntactically incorrect as you are using only one operand for binary operator subtraction which indeed is invalid.
So , it has thrown the error. hope this clarifies a bit.
Upvotes: 2