Davit Tvildiani
Davit Tvildiani

Reputation: 1965

C++ Structure Declaration and usage compiler error

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?

Upvotes: 1

Views: 1330

Answers (4)

CB Bailey
CB Bailey

Reputation: 793239

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;

Upvotes: 6

phoxis
phoxis

Reputation: 61990

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;
}

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92381

No it doesn't. In C you would write

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

Note the typedef.

Upvotes: 1

Lou Franco
Lou Franco

Reputation: 89242

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.

Upvotes: 1

Related Questions