constexpr initialization of global variable [duplicate] - c++

This question already has answers here:
When are static and global variables initialized?
(4 answers)
Closed 3 years ago.
If I have a variable declared with storage ie int x; and initialize it with a call to a constexpr function will it have the value determined before any code in main starts executing.
constexpr int get_value() { return 5;}
int x = get_value();
int main() {
return x;
};

In C++20, you have constinit for that:
constexpr int get_value() { return 5;}
// Still mutable, not constexpr but
// initialized with a value at compile time.
constinit int x = get_value();
int main() {
return x;
};

Related

What is the purpose of marking the set function (setter) as constexpr? [duplicate]

This question already has answers here:
What is the use of a constexpr on a non-const member function?
(2 answers)
Closed 4 years ago.
I cannot understand the purpose of marking the setter function as constexpr, that is allowed since C++14.
My misunderstanding comes from the next situation:
I declare a class with a constexpr c-tor, and I am about to use it in a constexpr context, by creating a constexpr instance of that class constexpr Point p1. An object p1 now is constant and its value could not be changed, so the constexpr setter could not be called.
On the other hand, when I create an instance of my class Point in a non-constexpr context Point p, I can call the setter for that object, but now setter will not execute at compile-time, because the object is not constexpr!
As a result, I do not understand how can I enhance the performance of my code using constexpr for setters.
This is the code that demonstrates calling a constexpr setter on an non-constexpr object, that means run-time computation, instead of the compile-time:
class Point {
public:
constexpr Point(int a, int b)
: x(a), y(b) {}
constexpr int getX() const noexcept { return x; }
constexpr int getY() const noexcept { return y; }
constexpr void setX(int newX) noexcept { x = newX; }
constexpr void setY(int newY) noexcept { y = newY; }
private:
int x;
int y;
};
int main() {
Point p{4, 2};
constexpr Point p1{4, 2};
p.setX(2);
}
Could anyone help me to understand what is the purpose of marking the setter function as constexpr?
Basically it is nice when you have to deal with constexpr function.
struct Object {
constexpr void set(int n);
int m_n = 0;
};
constexpr Object function() {
Object a;
a.set(5);
return a;
}
constexpr Object a = function();
The idea is to be able to perform compile time initialization within another functions that will be executed at the compile time. It is not done to be applied on constexpr object.
Another things to know is that constexpr member functions are not const member functions since C++14 :).
The need arise with new constexpr rule with C++14: inside constexpr function, you can now use multiple statements, including for loops and control flow.
Here's an example:
constexpr int count5(int start) {
int acc = 0;
for (int i = start ; i<start+5 ; ++i) {
acc += i;
}
return acc;
}
constexpr int value = count5(10); // value is 60!
As you can see, we can do many mutation to variable in a constexpr context. The compiler becomes like an interpreter, and as long as the result of the constexpr fonction is consistent and you don't mutate already computed constexpr variables, it may mutate the values during the interpretation.
A function with constexpr qualifier will evaluate the return of the function at compile time, which can significantly boost performance of a program (no extra computation, no instruction counter jumping, etc.). There are a few requirements to qualify a function thusly, so check out this explanation from IBM.

Why can't I assign const int in struct constructor? [duplicate]

This question already has an answer here:
Unable to initialize private const member [duplicate]
(1 answer)
Closed 4 years ago.
Why can't I do this in C++?
struct SomeStruct
{
public:
SomeStruct(const int someInt)
{
m_someInt = someInt;
}
private:
const int m_someInt;
};
Should the private field just be a regular integer?
You're assigning someInt to m_someInt, which is illegal. But initialization is okay.
struct SomeStruct
{
public:
SomeStruct(const int someInt) : m_someInt(someInt)
{
}
private:
const int m_someInt;
};
More info: Constructors and member initializer lists
Value cannot be assigned to a const storage. It can be only initialized. In case of class member variable it would be done in initialization list.
struct SomeStruct
{
public:
SomeStruct(const int someInt) : m_someInt(someInt)
{
}
private:
const int m_someInt;
};
Sometimes in-class initialization is enough:
template <int Val>
struct SomeStruct
{
public:
private:
const int m_someInt = Val;
};
Usually confusion stems from the fact that programmer doesn't see difference between two cases:
// 1) Declaring storage of int object that initially contains value 5
int a = 5; // It's a declaration.
// 2) Declaring storage of int object that contains undetermined value
int b; // Declaration
b = 5; // Assigning a value to it. It's a statement.
In your case m_someInt = someInt; is a statement that expects lvalue before =, and m_someInt is not a legal lvalue because it is const.

why default initialization using parentheses is not permissible in c++? [duplicate]

This question already has an answer here:
Why can in-class initializers only use = or {}? [duplicate]
(1 answer)
Closed 5 years ago.
This is the example from Effective modern c++.
class Widget {
…
private:
int x{ 0 }; // fine, x's default value is 0
int y = 0; // also fine
int z(0); // error!
};
direct initialization using ()
Inside the class treats the below
int z(0);
As a function as and expects parameter .As result error
Expected parameter declarator
alternatively can be done
class Widget {
private:
int x{ 0 };
int y = 0;
int z;
public:
Widget():z(0){}
};

What does v=0 in function parameters means [duplicate]

This question already has answers here:
assignment operator within function parameter C++
(3 answers)
Closed 5 years ago.
Here is a modified code from geeks for geeks.
#include<iostream>
using namespace std;
class Test {
int value;
public:
Test(int v = 0) {value = v;}
int getValue() {return value;}
};
int main() {
Test t(20);
cout<<t.getValue();
return 0;
}
What does parameter in function Test(int v=0) means?
That is default value for v parameter, which is the v variable will use that value if there is no value passed

What is the difference of const and static const? [duplicate]

This question already has answers here:
Const vs Static Const
(2 answers)
What is the difference between static const and const?
(4 answers)
Closed 8 years ago.
The following statements are both valid:
static const A = 2;
const B = 3;
What is the difference of declaring the first or the second?
If the static const were to be declared inside a class it'd accesible from the class and any instance of the class, so all of the would share the same value; and the const alone will be exclusive for every instance of the class.
Given the class:
class MyClass {
public:
static const int A = 2;
const int B = 4;
};
You can do this:
int main() {
printf("%d", MyClass::A);
/* Would be the same as */
MyClass obj;
printf("%d", obj.A);
/* And this would be illegal */
printf("%d", MyClass::B);
}
Check it out here on Ideone.
Static means the entire class only shares 1 const, where non-static means every instance of the class has that const individually.
Example:
class A{
static const a;
const b;
}
//Some other place:
A m;
A n;
Objects m and n have the same a, but different b.