Dynamically initializing a static value in C vs C++ [duplicate] - c++

This question already has answers here:
Difference between initialization of static variables in C and C++
(3 answers)
Closed 3 years ago.
#include <stdio.h>
int b(){
return 5;
}
int main(){
static int a = b();
return 0;
}
Above code doesn't compile in C with this error:
error: initializer element is not a compile-time constant
but compiles fine in C++. What are the differences between initializing static values in C and C++?

From cppreference:
Variables declared at block scope with the specifier static or thread_local (since C++11) have static or thread (since C++11) storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.
So, in C static is initialized at startup, while in C++ during the first time the code passes through this section of code.
This will allow assignment of a return from a function in C++ which would be impossible in C since C would need to know the value before the program starts to run...
I hope this helps
Lior

Related

Declaration of variable in C++ [duplicate]

This question already has answers here:
Direct Initialization vs Copy Initialization for Primitives
(4 answers)
Closed 5 years ago.
Recently I saw a quite old code in C++, where int var(12) was used instead of int var=12. Why does it work? And should I avoid writing this style of declaration?
There are three ways of initializing variables are valid in C++.
type identifier = initial_value;
For example, to declare a variable of type int called x and initialize it to a value of zero from the same moment it is declared, we can write:
int a=5; // initial value: 5
type identifier (initial_value);
A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (()):
int b(3); // initial value: 3
type identifier {initial_value};
Finally, a third method, known as uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011):
int c{2}; // initial value: 2
You should check Documentation section Initialization of variables

C++ self-referencing array?

I accidentally created a bug in a program by self-referencing in an array. Here's a very simplified demo program similar in concept:
#include <iostream>
using namespace std;
int kTest[] = {
kTest[0]
};
int main() {
cout << kTest[0] << endl;
}
I was surprised that I received neither a compiler error or even a warning on this code! In my case it ended up producing unpredictable output. Is it accessing garbage memory?
I was curious about under what circumstances this would have well-defined output (if ever!).
Edit: Does it make a difference if kTest is static? What about const? Both?
int kTest[] = {
kTest[0]
};
is similar to, if not exactly same as
int x = x;
It will be undefined behavior, if declared locally in a function.
It seems to be well defined when kTest is a global variable. See the other answer for additional details.
I'm not so sure this is undefined. Quote from the current draft:
[basic.start.static]/3
If constant initialization is not performed, a variable with static
storage duration ([basic.stc.static]) or thread storage duration
([basic.stc.thread]) is zero-initialized ([dcl.init]). Together,
zero-initialization and constant initialization are called static
initialization; all other initialization is dynamic initialization.
Static initialization shall be performed before any dynamic initialization takes place.
To me it looks like kTest is already zero-initialized when the dynamic initialization starts, so it may be defined to initialize to 0.

gcc runtime declaration of static and auto variables [duplicate]

This question already has answers here:
Why can't the size of a static array be made variable?
(4 answers)
Closed 8 years ago.
I am compiling my C code using the gcc compiler
My code is
main()
{
int i;
scanf("%d",&i);
int a[i];
}
... and it executes it without any warning. However, if I use:
main()
{
int i;
scanf("%d",&i);
static int a[i];
}
... I get an error message saying the size of array is not constant.
If execution of program starts at main function it should not give such error.
and if static data is allocated first before start of main(), how is the compiler able to generate such errors during during compile time?
Variables length arrays are not allowed to be static from the draft C99 standard section 6.7.5.2 Array declarators paragraph 2 says (emphasis mine):
An ordinary identifier (as defined in 6.2.3) that has a variably modified type shall have
either block scope and no linkage or function prototype scope. If an identifier is declared to be an object with static storage duration, it shall not have a variable length array type.
In C++ variable length arrays are not part of the standard and are a compiler extension but gcc should be be following the C99 rules there as well.

On which occasions will c++ initialize variables with zero? [duplicate]

This question already has answers here:
Default variable value
(10 answers)
Closed 9 years ago.
Every variable should be properly defined and initialized(assign a value to it) before being used. However under some circumstances, c++ will set variables with a default value of zero. Like the case below.
class A{
...
static int val;
...};
//int val = 10; //This is the usual definition.
int val;//Definition without assigning a value.
...
A a; //a class A object
std::cout<<a.val;
The result would be zero. Obviously, the compiler did something to initialize variable a.val to zero. I am curious about when will they do this generally?
http://en.cppreference.com/w/cpp/language/zero_initialization
Zero initialization is performed in the following situations:
For every named variable with static or thread-local storage duration, before any other initialization.
As part of value-initialization (i.e. with an empty pair of parentheses or braces) sequence for non-class types and for members of value-initialized class types that have no constructors.
When a character array is initialized with a string literal that is too short, the remainder of the array is zero-initialized.

variable zero-initialization - undefined behaviour or not [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is this self initialization valid?
Is this a well-defined C/C++ program or not?
int foo = foo;
int main()
{
}
Would foo be zero-initialized, or is it undefined behaviour?
It is an ill-formed C program. In C initializers for objects with static storage duration must be constant expressions. The foo on the right-hand side is not a constant expression.
In C++ it is well-formed and has defined behavior, because of zero-initialization of objects with static storage duration (which takes place before any other initialization).
Static/global variables are initialized with 0. Thus:
int ThisIsZero;
int main(void)
{
static int AndSoIsThis;
int ButThisIsNotInitialized;
...
};
It doesn't even compile in C. You cannot initialize global variables other than using compile time constants.
That does not compile - and what whats the point of the question?