Declaration Statements

Declaration Statements - A special case is used with for...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Declaration Statements In C, when you write a function, all the declarations of local variables must appear at the top of the function or at the beginning of a block: void f() { int x; /* . .. */ while (x) { int y; /* . .. */ } } Each such variable has a lifetime that corresponds to the lifetime of the block it's declared in. So in this example, x is accessible throughout the whole function, and y is accessible inside the while loop. In C++, declarations of this type are not required to appear only at the top of the function or block. They can appear wherever C++ statements are allowed: class A { public: A(double); }; void f() { int x; /* . .. */ while (x) { /* . .. */ } int y; y = x + 5; /* . .. */ A aobj(12.34); } and so on. Such a construction is called a "declaration statement". The lifetime of a variable declared in this way is from the point of declaration to the end of the block.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: A special case is used with for statements: for (int i = 1; i <= 10; i++) ... /* i no longer available */ In this example the scope of i is the for statement. The rule about the scope of such variables has changed fairly recently as part of the ANSI standardization process, so your compiler may have different behavior. Why are declaration statements useful? One benefit is that introducing variables with shorter lifetimes tends to reduce errors. You've probably encountered very large functions in C or C++ where a single variable declared at the top of the function is used and reused over and over for different purposes. With the C++ feature described here, you can introduce variables only when they're needed....
View Full Document

Page1 / 2

Declaration Statements - A special case is used with for...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online