-2

The following code containing a while loop compiles in C++.

#include <iostream>
using namespace std;

int main() {
    while (int i = 5)
    {
        break;
    }
    return 0;
}

However, the following equivalent C code results in an error if compiled in C:

#include <stdio.h>

int main() {
    while (int i = 5)
    {
        break;
    }
    return 0;
}

Compiler output:

> prog.c: In function 'main': prog.c:5:9: error: expected expression
> before 'int'   while (int i = 5)prog.c: In function 'main':
> prog.c:5:9: error: expected expression before 'int'   while (int i =
> 5)

Why does this happen? I tried to look up the documentation for the while loop in C, but haven't been able to locate that either.

lifebalance
  • 1,846
  • 3
  • 25
  • 57
  • 5
    `Valid C++ code does not compile in C` And, so what? There are zillions of valid C++ code examples that do not compile in C. – PaulMcKenzie May 10 '15 at 04:29
  • 2
    I don't think you deserve down-voting for this question. C and C++ are commonly lumped together, so it is understandable you would confuse their features. Probably no one studies `C` anymore, but if you are familiar with C++, it won't take an hour to understand what the C subset is. – wallyk May 10 '15 at 04:31
  • @PaulMcKenzie If you prefer a better title, go ahead and change it. Stop being nasty! – lifebalance May 10 '15 at 04:50
  • @wallyk Thank you for your "upvote", if you've already done it. – lifebalance May 10 '15 at 05:54
  • @wallyk: C isn't a subset of C++. – R.. GitHub STOP HELPING ICE May 10 '15 at 06:18
  • 1
    @lifebalance My comment came before you edited your question to add the C code. If you initially stated "I have this C++ code and I know it won't compile as C code, so I did this in C and am having a problem", then that would make much more sense than your initial, unedited post. – PaulMcKenzie May 10 '15 at 15:17
  • @PaulMcKenzie I shall have to be more comprehensive in my future posts. Meanwhile, it is "holier-than-thou" comments like yours that are a major cause for SO turn-off and also result in undeserving down-votes for me. Sigh. – lifebalance May 10 '15 at 18:22

5 Answers5

4

C and C++ are different languages. <iostream> is not part of C library, and using and namespace are C++ keywords only. Don't mix the languages, as they are not at all the same.

Also, as @sasquatch mentioned, it is illegal in C to declare a variable in the while condition.

You should not expect C++ code to compile in C. You should also not expect the other way around, since C is not a proper subset of C++.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • I meant to write "equivalent" code in C. Will update the question suitably. – lifebalance May 10 '15 at 04:52
  • @lifebalance In this case it's just the `while` issue then. Anyway, there are many other differences, for example, `int* p = malloc(...)` works in C (and it is [the recommended way of doing it](http://stackoverflow.com/q/605845/3093378)), but needs a cast in C++ etc. – vsoftco May 10 '15 at 04:55
  • If the `for` loop allows for variable initialization in C, why not allow it in the `while` loop as well? – lifebalance May 10 '15 at 05:06
  • In any case, I added links to the C++ and C language documentations for the while loop as a separate answer. – lifebalance May 10 '15 at 05:53
  • 1
    @lifebalance: C only allows a declaration in clause-1 of the `for` statement. The expression in a `while` loop is analogous to the controlling expression (expression-2) of the `for` statement where a declaration is not legal and would not even make sense because the value of the expression is needed and a declaration has no value. – R.. GitHub STOP HELPING ICE May 10 '15 at 06:22
  • @R Your comment **completes** the information available in the documentation as well. – lifebalance May 10 '15 at 06:28
3

In C++, a condition is tested for before each iteration of a while loop. Verbatim from the C++ reference:

condition - any expression which is contextually convertible to bool or a declaration of a single variable with a brace-or-equals initializer. This expression is evaluated before each iteration, and if it yields false, the loop is exited. If this is a declaration, the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.

Whereas in C, an expression is tested for before each iteration of a while loop. Verbatim from the C reference:

expression - any expression of scalar type. This expression is evaluated before each iteration, and if it compares equal to zero, the loop is exited.

lifebalance
  • 1,846
  • 3
  • 25
  • 57
2

In C, the while expects an expression inside the parenthesis. What you have is a declaration of the variable. You would have to declare the variable before the loop and then write the expression as i == 5 to compile in C.

This post covers what C expects compared to C++ in more detail. The same rules that they explain for an if also applies to a while.

Community
  • 1
  • 1
mas4
  • 989
  • 1
  • 8
  • 20
  • I did refer to that SO post even before asking this question. Meanwhile, found links to the language documentations for the `while` loop which clarifies the difference. Please refer my answer below. – lifebalance May 10 '15 at 05:56
2

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.:)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

There are multiple issues with the code you have above.

First off you may want to get rid of both the name space and the header. They are not even being used in the code and are not able to be read by the c compiler either.

Second, you cannot define variable types in any looping commands. For example while (int i != 5) and for (int i =0 ...) is invalid in c. You have to define the variable before the loop.

Finally, although I believe the c++ standard allows you to define a variable in a while statement, I highly suggest not doing so. Its semi confusing to have a comparison statement mixed with a variable definition ie: int x, bool y, double z, etc. etc.

Zachary Kraus
  • 1,051
  • 10
  • 21
  • 1
    You are right and in support of your point, here is a sample code - http://ideone.com/rn379R - I still remain curious as to what conditions under which the declaration would actually come in handy. – lifebalance May 10 '15 at 06:33
  • @lifebalance that code makes my point exactly. Thank you. I am also curious as well if there is a condition where a declaration in the while statement would make any sense. – Zachary Kraus May 10 '15 at 23:51
  • 1
    http://ideone.com/z1LYRl - it is pretty much C code, but compiled in C++ with declaration of `next` within the `while` scope. Some more interesting responses on the same topic at http://stackoverflow.com/q/190748/307454 – lifebalance May 14 '15 at 09:11