Google Interview Question
Software Engineer / Developersactually there is 1 problem. length of array b should be known at compile time and variables are allocated at run time.
As far as return type of main is concerned. Its the only function in c++ which implicitly gets return type.
Note: with c++11 this code:
using namespace std;
constexpr int a[]={1,2,3,4,5};
int b[a[2]];
Becomes perfectly valid.
looks like, the question is given to misled you to think that, b[a[2]] does not work, but it does work perfectly. b[a[2]] will be evaluated as b[3] and so, b will be created as an array of 3 elements. The only visible problem with the code is that main does not return any int value.
for static allocations like the one "int b[n];" n should be a constant positive integer or a const int variable(positive) defined before "int b[n];" statement.
I run following program but I have not seen any error in LINUX gcc compiler.
#include <iostream>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5};
int b[a[2]];
return 0;
}
Folowing code thrown an error "Error: variable-sized object ‘b’ may not be initialized "
#include <iostream>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5};
int b[a[2]] = {1};
return 0;
}
any one please explain , why I am getting error in second program and no tin first program ?
Hi ,
a and b are global variables. Their sizes are allocated whenever they are declared whereas in the case of local variables the size are only allocated when they are defined.
So in this case the compiler is unable to decide what size to allocate.
Deep jumping in references are not allowed at compile time. In case of
const int a;
int b[a];
one direct reference to the variable. But in case of
const int a[] = {0,1,2};
int b[a[1]];
first 1 store in temporary variable then ->used in a[1] ->first reference
second b[a[1]] ->second reference (depth)
in C++, const can be used with complex data types like arrays , structures, but it does not mean that you can access the value at compile time. It means the storage is constant and cannot be changed , but retrieving what is present at that storage at compile time is not allowed.Its allowed for simple types like int, char, float.
The Problem in the give code [original code] is that both a[] and b[] are global variables and so there is no order of there construction. a[] can get constructed first as is happening with siva.sai in gcc compiler. But he is lucky. If any compiler writes the code to create global objects in such a way that b[] is created before a[] then "boom"!.
- Sourav Sain October 04, 2010We should not write such a code assuming order of creation of global variables to be in certain way. Standard does not define any such order. For local variables, yes you can guess the order of creation of objects [but these days smart optimizers in compiler coded tweek with them too!]