Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of const in c++

I am new to C++.I was going through a C++ book and it says

const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // Illegal

It says the declaration of the float variable is invalid during compilation.Why is that?

Suppose if we use

int i = 3;
float f[i];

It works.

What is the problem with the first situation?

Thanks.

like image 544
starkk92 Avatar asked Sep 25 '13 13:09

starkk92


People also ask

What is the use of const in C?

The const keyword allows a programmer to tell the compiler that a particular variable should not be modified after the initial assignment in its declaration.

What is the use of const statement?

The Const statement can declare the data type of a variable. You can specify any data type or the name of an enumeration.

What is the benefit of using const?

Constants can make your program more readable. For example, you can declare: Const PI = 3.141592654. Then, within the body of your program, you can make calculations that have something to do with a circle. Constants can make your program more readable.


2 Answers

So the first is illegal because an array must have a compile-time known bound, and i[3], while strictly speaking known at compile time, does not fulfill the criteria the language sets for "compile-time known".

The second is also illegal for the same reason.

Both cases, however, will generally be accepted by GCC because it supports C99-style runtime-sized arrays as an extension in C++. Pass the -pedantic flag to GCC to make it complain.

Edit: The C++ standard term is "integral constant expression", and things qualifying as such are described in detail in section 5.19 of the standard. The exact rules are non-trivial and C++11 has a much wider range of things that qualify due to constexpr, but in C++98, the list of legal things is, roughly:

  • integer literals
  • simple expressions involving only constants
  • non-type template parameters of integral type
  • variables of integral type declared as const and initialized with a constant expression
like image 141
Sebastian Redl Avatar answered Nov 09 '22 13:11

Sebastian Redl


Your second example doesn't work and it shouldn't work. i must be constant. This works

const int i = 3;
float f[i];
like image 3
wl2776 Avatar answered Nov 09 '22 13:11

wl2776