0
#include <iostream>

int a = 9;
int *p;
p = &a;

int fun();

int main()
{
    std::cout << fun();
    return 0;
}

int fun()
{
    return *p;
}

Why does this code give the error:

expected constructor, destructor, or type conversion before '=' token|

Whereas this code runs OK:

#include <iostream>

int a = 9;
int *p = &a;

int fun();

int main()
{
    std::cout << fun();
    return 0;
}

int fun()
{
    return *p;
}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Gautam Kumar
  • 1,162
  • 3
  • 14
  • 29
  • Please take care to [format your code as described in the FAQs](http://meta.stackexchange.com/q/22186) – razlebe Jul 01 '11 at 10:23

3 Answers3

12

You are allowed to declare and initialize variables/types globally not assign them.
main() is the start of the C++ program and assign statements would have to be inside main.

C++03 Standard: section $3.6.1/1:

A program shall contain a global function called main, which is the designated start of the program.

If you coming from a Scripting background, you should note that C++ is different from Scripting languages in the way that you can declare items outside the bounds of designated start of program (main()), but you cannot do any processing(assignment or other statements).

Alok Save
  • 202,538
  • 53
  • 430
  • 533
5

The assignment statement

p=&a;

is illegal in the place you've put it. Assignments must take place inside the body of a function.

The line

int *p=&a;

is legal because you're declaring and initialising a variable.

This question is about a similar problem.

Community
  • 1
  • 1
razlebe
  • 7,134
  • 6
  • 42
  • 57
2

One of the confusing things about the language: Two basic constructs that use the same operator, =, meaning different things.

In the first case the = is just part of the syntax for initialisation, it isn't really operator= at all in that it isn't an assignment, although the consequence (post-condition) is the same: the variable ends up with that value. It is just different how it gets there.

CashCow
  • 30,981
  • 5
  • 61
  • 92