I understood result of
int nData = 10;
printf("%d", sizeof(nData + 2.0));
is "8"
why each result of
int nData = 10;
printf("%d", sizeof(nData = 2.0));
printf("%d", sizeof(nData += 2.0));
is not 8 but 4? Why nData
cannot be 12.0
or 12
by sizeof(nData += 2.0)
?
Because 2.0 is a constant of type double
, the expression nData + 2.0
has type double
as per the "usual arithmetic conversions" specified in section 6.3.1.8 of the C standard:
First, if the corresponding real type of either operand is long double , the other operand is converted, without change of type domain, to a type whose corresponding real type is long double.
Otherwise, if the corresponding real type of either operand is double , the other operand is converted, without change of type domain, to a type whose corresponding real type is double
So sizeof
evaluates to the size of a double
.
In the case of nData = 2.0
and nData += 2.0
, each expression has type int
because that is the type of the left-hand side of the assignment. So sizeof
evaluated to the size of an int
.
Also, the operand of the sizeof
operator is evaluated for its type only at compile time. This means that any assignment or increment is not evaluated at runtime. So in your second example, nData
will still have the value 10 after the two lines that use sizeof
. The only time the operand of sizeof
is evaluated at run time is if the operand is a variable length array.
Why
nData
cannot be12.0
or12
bysizeof(nData += 2.0)
?
Well, sizeof
is a compiler time operator, and it operates on the data type, not the value.
In other words, except when the argument is VLA, the operand of the sizeof
is not evaluated.
Quoting C11
, chapter §6.5.3.4
The
sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
So, in your case,
printf("%d", sizeof(nData + 2.0)); // data == int, 2.0 == double
is the same as
printf("%d", sizeof(double)); // as the resulting "type" of the addition,
// 'int + double' would be 'double'
which should better be
printf("%zu", sizeof(double)); //not %d
as sizeof
yields size_t
type.
Also, regarding the 2.0
being of type double
, from chapter §6.4.4.2
A floating constant has a significand part that may be followed by an exponent part and a suffix that specifies its type. The components of the significand part may include a digit sequence representing the whole-number part, followed by a period (.), followed by a digit sequence representing the fraction part. [...]
and
An unsuffixed floating constant has type
double
. [...]
Thus, a constant value like 2.0
has the type double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With