Reputation: 6326
It seems that we can not give a default value for struct members in c++,but I find that code as below can compile and run, why? Am I missing something?
struct Type {
int i = 0xffff;
};
Program:
#include <iostream>
using namespace std;
struct Type {
int i = 0xffff;
};
int main() {
// your code goes here
Type val;
std::cout << val.i << std::endl;
return 0;
}
Upvotes: 0
Views: 1808
Reputation: 7663
It is going to depend on the compiler you use.
For gcc and clang you need to pass the flag -std=c++11
to the compiler.
Support for member initializer and other c++11 features:
Upvotes: 1
Reputation: 5731
This is correct and introduced in C++11 standard. This concept is known as in-class member initializer
You can check Stroustrup FAQ link on this concept:
http://www.stroustrup.com/C++11FAQ.html#member-init
Upvotes: 0