dhulmul
dhulmul

Reputation: 750

Is it necessary that for external and static variables, the initializer must be a constant expression?

While reading "The C Programming Language" by Dennis M. Ritchie I came across this line:

For external and static variables, the initializer must be a constant expression.

I am unable to understand what constant expression means here because the below code compiles without any error, isn't the statement: static int a = n-1 , a non constant expression? Please point out what am I missing here. Thanks in advance.

#include<iostream>
using namespace std;

int main()
{   
int n;
cin>>n;

static int a = n-1;

return 0;
}

Upvotes: 0

Views: 209

Answers (3)

MobA11y
MobA11y

Reputation: 18900

file main.c contents

int main()
{
int n;

static int a = n-1;

return 0;
}

Output of g++ main.c

//Emptiness because it is valid C++

Output of gcc main.c

main.c: In function ‘main’:
main.c:6: error: initializer element is not constant

Upvotes: 0

user529758
user529758

Reputation:

It's necessary in C, but not in C++. They are different languages.

The code compiles as C++,

but not as C.


void foo() { this line is here because of stupid restrictions of Stack Overflow }

Upvotes: 5

RichieHindle
RichieHindle

Reputation: 281765

Your code is C++, not C. A very different language. The book's statement is true for C, but not for C++.

Upvotes: 1

Related Questions