开发者

What is the rule for declaration before use in C++?

开发者 https://www.devze.com 2023-03-21 11:57 出处:网络
My course notes say \"C++ requires declaration before use in a block and among types but not within a t开发者_开发技巧ype.\"

My course notes say "C++ requires declaration before use in a block and among types but not within a t开发者_开发技巧ype."

Is this what it means?

int f() {
   if (i)
     return i;
   int i = 1; //allowed?
   return 0;

}

//not allowed?
int g() {
    if (i)
      return i;
    return 0;
}

int i = 1; 


No. Both your examples are "in a block" and neither of those is allowed. If you try compiling your example code you'll get an error immediately.

However, this would be allowed:

class Foo {
    int f() {
        return i;
    }

    private:
    int i;
};

This is within a type and that's the important distinction.


Both of these are wrong. The correct form is this:

int f() {
   int i = 1;
   if (i)
     return i;
}

int f() { } is a block. You must declare i before it can be used in that block.


Both are not allowed. What is allowed though is the following:

struct F {
    void f()
    {
      if( i ) return i;
    }

    int i;
};

Here F is a type, a user-defined structure type. This is what meant by "within a type". Your examples are both on "within a block" case.


C++ requires declarations before usage in a block. However with in a struct/class this declaration is made implicitly whenever an object of this is made. A default constructor is called which allocates memory to its variables thereby negating the undefined type problem.

This is my understanding of the line.. If wrong please correct me as to how compiler comes to know of the reqd memory space for the derived data type members.

0

精彩评论

暂无评论...
验证码 换一张
取 消