There is a difference in the definition of the while statement in C++ and C.
In C++ the while statement is defined the following way
while ( condition ) statement
where in turn the condition is defined like
condition:
expression
attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list
As you can see apart from an expression the condition may be a declaration with some initializer. The value of ibitializer is converted to an expression of type bool
and the while statement is executed depending on the boolean value.
So in your C++ program the value of the initializer of the declaration in the condition of the while statement is equal to 5
while (int i = 5)
As it is not equal to zero then it is converted to boolean true
.
In C the while statement is defined the following way
while ( expression ) statement
As you can see yourself here is explicitly specified that only expressions may be used. C does not allow to use declarations in the while statement. So this statement
while (int i = 5)
will not be compiled in C.
It is not the only difference between C++ and C. For example this conditional operator below will be compiled in C++ and will not be compiled in C
int x = 10;
int y = 20;
( x < y ? x : y ) = 20;
Or this statement will be compiled in C++ and will not be compiled in C
int x;
int y = 20;
++( x = y );
The code snippet below will yield different results in C++ and C
if ( sizeof( 'A' ) == 1 ) puts( "They are equal" );
else puts( 'They are not equal" );
Or consider the following example
int x = 10;
void *vp = &x;
int *ip;
ip = vp;
This code snippet will be compiled in C and will not be compiled in C++. So you should be caution.
Moreover C and C++ have even different fundamental types. For example in C there is integer type _Bool
that is absent in C++. On the other in C++ there is type bool
and corresponding boolean literals false
and true
that is absent in C. In C++ there is pointer literal nullptr
that is absent in C. Or in C there are compound literals that are absent in C++. Or in C++ there is the range based for statement that is absent in C and so on.:)