Declarations

I l @ ve RuBoard

Declarations

C requires that all variables other than function parameters be declared at the beginning of a block, that is, just after an opening brace . C++ removes this restriction, and the C++ practice is to declare a variable at the point it first gets a value. C++ even allows you to declare a variable in the initialization slot of a for statement. For example, the following code is valid C++:

 #include <stdio.h> int main() {         puts("Enter a value for n:");         int n;                           /* valid C++, invalid C */         scanf("%d", &n);         for (int i = 0; i < n; i++)   /* valid C++, invalid C */         {                 puts("Thank you!");                 puts("Enter a word:");                 char word[40];            /* valid C++, invalid C */                 scanf("%s", word);                 printf("%s is ok.\n", word);         }         return 0; } 

It is not, however, valid C. So if you've found your compiler allows you to write code like the preceding example, it is working in the C++ mode.

C allows you to omit int in some declarations; C++ does not. However, omitting int in C is considered poor style and is forbidden in C9X. In the following, const is interpreted as const int , unsigned is interpreted as unsigned int , and floobie() has return type int .

 const que = 88;   /* poor style in C, illegal in C++ */ unsigned jay = 2; /* poor style in C, illegal in C++ */ floobie(double);  /* poor style in C, illegal in C++ */ 

Normally, it is an error to initialize an array using more values than the size of the array. However, C (but not C++) allows one exception. You can initialize an array of char to a string literal that is one character longer (counting the null character) than the array. In that case, the null character is not copied , so the array holds characters , but not a string:

 char rare[3] = "ton";         /* ok C, invalid C++      */ char rare[3] = {'t','o','n'}; /* C, C++ valid equivalent */ 
I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net