1

Here is my code:

#include <iostream>
using namespace std;

struct product {
  int weight;
  float price;
} apple, banana, melon; // can I declare like this ?????

int main()
{
  apple a;

}

When I compiled this sample, the compiler says:

struct.cpp|11|error: expected ';' before 'a'|

Same thing works fine in C language ...

What's wrong?

1
  • 1
    Ignoring the C++ syntax in the header and namespace (which aren't needed to reproduce the problem with the almost minimal code you have here), the code would not compile in C, either. While C and C++ are different languages, they are at least similar in that. Commented May 29, 2011 at 14:48

4 Answers 4

6

What you've done is declared apple, banana and melon as global instances of product whereas your main function indicates that you wanted to declare them as types. To do this you would use the typedef keyword in the declaration. (Although why do you need so many synonyms for struct product?)

This is not different from C. The only difference between C and C++ in your example is that in C++ product names a type whereas in C you have to specify struct product. (Apart from the more obvious fact that you can't have #include <iostream> or using namespace std; in C.)

E.g., declares apple, banana and melon as synonyms for struct product:

typedef struct product {
  int weight;
  float price;
} apple, banana, melon;
Sign up to request clarification or add additional context in comments.

Comments

1

apple isn't a type, it's a variable of the product struct type you declared.

typedef product apple;

would create a type called apple.

1 Comment

That's pure C++; in C, you'd need typedef struct product apple;, of course. Since the question is tagged C++ and not C, this a pure observation - not a criticism.
1

No it doesn't. In C you would write

typedef struct product {
   int weight;
   float price;
} apple;

Note the typedef.

Comments

1

How could the same code run in C? your code will give the same error in C also, it is incorrect.

in the main you have done: apple a where apple is not any type. It is a global struct product type variable.

To define a variable of your structure type do:

int main (void)
{
  struct product a;
}

Or if you want to name your struct with some name you can use typedef like

typedef struct product {
     int weight;
     float price;
} product;

and then

int main (void)
{
  product apple, a, whataver;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.