|
-
April 16th, 2010, 06:35 AM
#1
[RESOLVED] I do not why this compiles! confused
Hi,
I am sure that the size of c style arrays must be known at compile tim
but the code below compiles. I am using g++ 4.2.4 and really confused!
Code:
int main(){
int N = 5;
int x[N];
x[2] = 3;
}
-
April 16th, 2010, 06:45 AM
#2
Re: I do not why this compiles! confused
 Originally Posted by ar115
Hi,
I am sure that the size of c style arrays must be known at compile tim
but the code below compiles. I am using g++ 4.2.4 and really confused!
Code:
int main(){
int N = 5;
int x[N];
x[2] = 3;
}
The compiler sees that N is defined by the time you reach int x[N], N's value can only be 5, which means the size is known at compile time. The compiler does not necessarily need the size to be a const.
If you volatile the N, it would not compile.
Last edited by monarch_dodra; April 16th, 2010 at 06:48 AM.
-
April 16th, 2010, 06:50 AM
#3
Re: I do not why this compiles! confused
but it also works without setting the value of N like this
Code:
int main(){
int N;
int x[N];
}
-
April 16th, 2010, 06:52 AM
#4
Re: I do not why this compiles! confused
AFAIK that should not compile. The size of arrays must be a nonzero constant.
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
-
April 16th, 2010, 06:53 AM
#5
Re: I do not why this compiles! confused
Code:
int main()
{
int N = 5;
++N;
N*=2;
int i;
std::cin >> i;
if (i==1) ++N;
int x[N];
x[2] = 3;
std::cout << N << std::endl;
std::cout << sizeof(x) << std::endl;
}
Now I'm confused too, as this example clearly shows that the size of x is not only unkown at compile time, it is correctly (and dynamically) sized to 12*4 or 13*4 according to i.
-
April 16th, 2010, 07:06 AM
#6
Re: I do not why this compiles! confused
It is a g++ extension .. to turn off, compile with:
g++ -pedantic
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|