In C++, having primitive type (int
, double
, char
, ...) not-defined so undefined behaviour. There is no default value for primitive types, because they have no constructor. But the compiler is consistent giving default value (0
), when there is no context:
int main(){
int x;
std::cout << x << std::endl;
}
will always give 0
(compiled cc -lstdc++
).
However, having some context (i.e. not just printing it), the value is random:
#include <algorithm>
#include "student.hpp"
using std::max;
int main(){
int x;
Student_struck s = {.name = "john"};
std::cout << max(s.name.size(), (std::size_t)x) << std::endl;
}
here, the same compilation, but every time different result:
21898, 22075, 22020, 21906, ...
What is gcc implementation for primitive not-defined variables?
It is even more strange, that in comparison with C, I can have
#include <stdio.h>
int main(){
int i;
printf("%i\n",i);
}
And the compiler is always consistent, with giving 0
as default value. So the same compiler, but different language for the same primitive types give different results. I would really like to know what is the implementation for C++ library to handle non-defined primitive variables.
What is difference between primitive types in C vs in C++. I am not asking about the UB, but only how are those types defined in both language and difference between them