Does variable shadowing work on all compilers in C++? - c++

I ran this code on Leetcode.com but it prints random numbers. It works on my local machine, however. Anybody know if variable shadowing is supposed to work across all compilers?
int carry = 0;
if (1) {
int carry = carry + 1;
cout << carry << endl;
}

The shadowing is defined by the C++ standard, and must work on all conforming compilers.
Your code prints garbage, because carry in carry + 1 reads the new variable (which isn't initialized at that point yet, causing UB), not the old one.

As #HolyBlackCat mentioned:
The shadowing is defined by the C++ standard, and must work on all
conforming compilers.
So because carry inside carry+1 takes the new carry, and that carry isn't initialized, anything can happened, as it's Undefined Behavior (UB).
Mind you, UB doesn't mean that the output is random, it just mean that anything can be printed out (so it may be consistent), and in some case you will get the correct answer.
Edit:
To the question "Why isn't it reading the older "carry" if the inner carry is undefined yet?".
It is designed this way within compiler, as #Nikita Demodov mentioned:
(For some reason) A variable is declared once it's identifier is reached. That's why
the carry after the = is the newly declared carry, rather that the
carry outside the if.
And as said in this documentation:
You can hide names with global scope by explicitly declaring the same
name in block scope. However, global-scope names can be accessed using
the scope-resolution operator (::).
In other word, whenever there is a local variable defined with same name as that of a global variable, the compiler will give precedence to the local variable.

Related

Why can we use uninitialized variables in C++?

In programming languages like Java, C# or PHP we can't use uninitialized variables. This makes sense to me.
C++ dot com states that uninitialized variables have an undetermined value until they are assigned a value for the first time. But for integer case it's 0?
I've noticed we can use it without initializing and the compiler shows no error and the code is executed.
Example:
#include <iostream>
using namespace std;
int main()
{
int a;
char b;
a++; // This works... No error
cout<< a << endl; // Outputs 1
// This is false but also no error...
if(b == '0'){
cout << "equals" << endl;
}
return 0;
}
If I tried to replicate above code in other languages like C#, it gives me compilation error. I can't find anything in the official documentation.
I highly value your help.
C++ gives you the ability to shoot yourself in the foot.
Initialising an integral type variable to 0 is a machine instruction typically of the form
REG XOR REG
Its presence is less than satisfactory if you want to initialise it to something else. That's abhorrent to a language that prides itself on being the fastest. Your assertion that integers are initialised to zero is not correct.
The behaviour of using an uninitialised variable in C++ is undefined.
It isn't feasible or even possible to detect or prove that variable is used uninitialized in all cases. For example:
int a;
if (<complex condition>)
a = 0;
if (<another complex condition>)
a = 1;
++a;
Can there be case when both conditions are false? You wouldn't know, unless you do an extensive analysis of your program. Pointers to variables can be passed, multithreading might be involved, making analysis even harder.
So, the decision was made to trust the programmer and merely declare those UB.
Modern compilers can issue warnings in many cases of uninitialized variable usage, and you should always use maximum warning level.
Anything is possible when your code has undefined behavior.
Correct code does not contain undefined behavior. Using the value of an uninitialized variable is undefined behavior.
The concept of undefined behavior is not unique to C++, but in C++ it is more important than elsewhere because there are so many chances to write wrong code without getting a compiler error.
However, the compiler is your friend. Use it! For example with gcc -Wall -Werror should be your default to get the error message:
<source>: In function 'int main()':
<source>:9:6: error: 'a' is used uninitialized [-Werror=uninitialized]
9 | a++; // This works... No error
| ~^~
<source>:13:5: error: 'b' is used uninitialized [-Werror=uninitialized]
13 | if(b == '0'){
| ^~
cc1plus: all warnings being treated as errors
Though, not all cases of undefined behavior can be caught by warnings (that can be treated as errors).
C++ dot com states that uninitialized variables have an undetermined value until they are assigned a value for the first time. But for integer case it's 0?
The correct term is indeterminate. As you can see in the above compiler output, there is no difference for your int a;. When anything can happen then undefined behavior can look like correct behavior, nevertheless it must be fixed.
TL;DR: You cannot use the value of an uninitialized variable. Code that compiles without errors is not necessarily correct.
There is no way to "mark" a variable as being uninitialized unless you store an extra bit of information somewhere, or reserve a value in the range of values that the data type covers. Plus every reference to the variable would have to test for uninitializedness.
All of this is completely unacceptable.
Also note that automatic variables are not implicitly initialized to some value (say 0) because this has a cost at run-time, even if the variable is not used.
As others have stated it's not always feasible for the compiler to detect if the variable is uninitialized and C and C++ prefer performance in those cases.
However, there are some additional points:
There are dynamic checkers that will detect if any of your test-cases uses an uninitialized variable. That only works if you don't zero-initialize them "just in case".
In C++ you can mix statements and declarations, so instead of
int a,b,c;
...
c=2;
a=12*c;
b=...;
you can write:
...
int c=2;
int a=12*c;
int b=...;
and if you don't modify them further you can add const as well, and lambdas are also useful for this.
If you really need to represent a possibly uninitialized variable use std::optional<...>. It can avoid some of those 'possibly uninitialized' cases and can detect if you try to access it when uninitialized. But it has a cost.

C++ manipulators

I have started learning C++ and I think the language is great, but few things are baffling me while I am on my path learning it. In this example:
cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint);
In this example why do we type the whole setiosflags(ios::...) when the program still does the same if I only type showpoint without setiosflags?
Second question I have is simple. If we have the following:
int x=0;
cin>>x;
Why do we define a value for int if we later change it to something different than 0?
why do we type the wholesetiosflags(ios::...)when the program still does the same if I only type showpoint without setiosflags?
We don't, unless we want the program to be more verbose than necessary. As you say, streaming setioflags with a single flag is equivalent to streaming the flag itself. You might use setioflags if you have a pre-computed set of flags you want to set.
Why do we define a value for int if we later change it to something different than 0?
Again, we don't, unless we like unnecessary verbiage. But it's a good habit to initialise variables, to avoid undefined behaviour if you later change the code to assume it has been initialised.
Its optional and flexibility language provide, so either you can set manipulators using setiosflgas or as showing below:
float y= 1.45;
std::cout << std::fixed<<std::showpoint<<y;
Why insisting to initialize variables is because before C++11 these uninitialized variables can hold garbage value until you set value for them. And it may create unwanted issues and bugs. So better practice always initialize variables when you define it.
Since C++11 all fundamental data types are initialized to zero if you use explicit constructor as follows:
int i2 = int(); // initialized with zero
int i3{}; // initialized with zero (since C + + 11)
The stream manipulator std::setiosflags(ios_base::fmtflags mask)- is a function that sets the format flags specified by parameter mask. It can be used for multiple flags simultaneously, by using binary AND : &. It probably exists to provide full/complete functionality of the class that belongs to. Now regarding your question:
If you can access a flag(member) directly, why bother using a function(setter)?
I can't think of any reason why you shouldn't. However have in mind that manipulators are global functions and these constants, ios_base::fmtflags, are member constants. For more information on manipulators check this.
Regarding the second question: you initialize a variable when you define it to avoid undefined behaviour in case you use it, by mistake, before assigning it any value. Local variables need initialization, global variables are initialized by default.

Initialize primitives or not - c++

When do I need to initialize variables in c++? Some people assert that its important but maybe this is more an issue in c-language?
I am refferering to primitives i.e. char, int, long, double
Let say I have the following code-snippet
int len;
double sum, mean;
char ch;
while (true) {
// here I use these primitives where they are initialized.
}
So - should I initialized these primitives as a good programming pratice here?
In c++ compiler usualy do not initialize local (automatic) variables. These variables are created on the stack and they are filled with random values. Usualy you do not need to inicialize variables but read carefuly what the compiler says. Try:
int main() {
int x;
x=x+1;
}
and compile it with -Wall switch (I'm using gcc). When the message
x.cpp: In function ‘int main()’:
x.cpp:3:6: warning: ‘x’ is used uninitialized in this function [-Wuninitialized]
x=x+1;
is written, then it would be better to initialize such variable.
The problem is, of course, the use of unitialised variables as in
int x;
int y=1+x; // oops what is y?
AFAIK, the language standard allows the compiler to initialise x to 0, but also to leave it unitialised. In any case, most optimisations (-O) will omit an initialisation in the above situation.
If you use full warning compiler flags (e.g. -Wall -Wextra -pedantic) the compiler will almost certainly spot the usage of unitialised variables (it will also warn about usage of unitialised variables in library header files, such as boost headers -- the boost developers appear to not use such useful diagnostics).
In general, whether or not to initialise all variables is a matter of style. I would provide an explicit initialisation whenever there is a sensible initial value for a variable and/or if there is the danger of it being used unitialised. Different from C, the possibility of unitialised variables is quite rare in C++, in particular when passing by return value (including move semantics).
You should initalize all variables to prevent: "trash in input - trash in output".
When do I need to initialize variables in c++?
You should initialize local variables with a sensible value when you define them. If you cannot give a variable a sensible value yet, then you should probably define it later.
The goal here is to minimize the amount of state in your functions in order to make them easier to understand. When all variables are defined at the beginning of the function, you don't know what they are used for. When they are defined at the point they are needed, it's clear that they are not used before that point. This also helps to limit the scope in which variables are declared (e.g. inside the loop instead of before it, thus less state outside the loop) and it allows you to define more variables as const (thus not adding state).

Function and declaring a local variable

Just having an conversation with collegue at work how to declare a variables.
For me I already decided which style I prefer, but maybe I wrong.
"C" style - all variable at the begining of function.
If you want to know data type of variable, just look at the begining of function.
bool Foo()
{
PARAM* pParam = NULL;
bool rc;
while (true)
{
rc = GetParam(pParam);
... do something with pParam
}
}
"C++" style - declare variables as local as possible.
bool Foo()
{
while (true)
{
PARAM* pParam = NULL;
bool rc = GetParam(pParam);
... do something with pParam
}
}
What do you prefer?
Update
The question is regarding POD variables.
The second one. (C++ style)
There are at least two good reasons for this:
This allow you to apply the YAGNI principle in the code, as you only declare variable when you need them, as close as possible to their use. That make the code easier to understand quickly as you don't have to get back and forth in the function to understand it all. The type of each variable is the main information about the variable and is not always obvious in the varaible name. In short : the code is easier to read.
This allow better compiler optimizations (when possible). Read : http://www.tantalon.com/pete/cppopt/asyougo.htm#PostponeVariableDeclaration
If due to the language you are using you are required to declare variables at the top of the function then clearly you must do this.
If you have a choice then it makes more sense to declare variables where they are used. The rule of thumb I use is: Declare variables with the smallest scope that is required.
Reducing the scope of a variable prevents some types errors, for example where you accidentally use a variable outside of a loop that was intended only to be used inside the loop. Reducing the scope of the variable will allow the compiler to spot the error instead of having code that compiles but fails at runtime.
I prefer the "C++ style". Mainly because it allows RAII, which you do in both your examples for the bool variable.
Furthermore, having a tight scope for the variable provides the compile better oppertunities for optimizations.
This is probably a bit subjective.
I prefer as locally as possible because it makes it completely clear what scope is intended for the variable, and the compiler generates an error if you access it outside the intended useful scope.
This isn't a style issue. In C++, non-POD types will have their constructors called at the point of declaration and destructors called at the end of the scope. You have to be wise about selecting where to declare variables or you will cause unnecessary performance issues. For example, declaring a class variable inside a loop may not be the wisest idea since constructor/destructor will be called every iteration of the loop. But sometimes, declaring class variables at the top of the function may not be the best if there is a chance that variable doesn't get used at all (like a variable is only used inside some 'if' statement).
I prefer C style because the C++ style has one major flaw to me: in a dense function it is very hard on eyes to find the declaration/initialization of the variable. (No syntax highlighting was able yet to cope reliably and predictably with my C++ coding hazards habits.)
Though I do adhere to no style strictly: only key variables are put there and most smallish minor variables live within the block where they are needed (like bool rc in your example).
But all important key variables in my code inevitably end up being declared on the top. And if in a nested block I have too much local variables, that is the sign that I have to start thinking about splitting the code into smaller functions.

why a variable declared but not used may cause a error?

If i declare a variable but not use it later in the program, the complier will give me a warning, and since "every warning should not be ignored", why the warning is there? and how can it cause a error? thanks!
First, a minor point: declaring a variable that's never used is a waste of memory, and thus is itself a bug.
Second, and more importantly: you took the trouble of writing out a declaration for a variable you then never used. Since you would not have bothered to declare a variable if you had no plan to use it, this suggests you've forgotten to use it! Is it possible you typed the wrong variable name in its place? Is it possible you forgot to perform a critical calculation whose result you'd store in that variable?
Of course, you might just have declared something you ended up not needing, which is why it's a warning and not an error, but it's easy to see situations where that warning can point you to an important piece of missing code, which would indeed be a bug.
It's there because maybe you meant to use the variable. You generally don't declare a variable and then use not it :)
It's a helpful warning, and it exists in most languages.
It may assist in detecting typos, where you accidentally used another variable instead of the one you meant to, this warning will remind you of the one that you haven't used :)
It doesn't cause an error. It causes a warning (normally only at higher levels on most compilers) because the variable isn't doing anything, which might indicate that you intended to use it but didn't. Sometimes that might indicate that your code is behaving incorrectly.
It's not that the code could fail as it is, just that the compiler's trying to warn you that you've done something a little odd.
It may indicate the presence of a bug, a variable that is declared but unused is obviously a programming error, since why else would it be there at all?
Are you asking about something like this?
int function() {
double x;
return 42;
}
There's a warning saying the variable x is unused because, well, it's unused. It is a warning because if a variable is unused, it does nothing*.
You may fall into this warning if you mistype or accidentally shadow a variable. For instance:
void printArgument10Times(int i) {
for(int i = 0; i < 10; ++i) {
std::cout << i << std::endl;
}
}
// ...
printArgument10Times(42);
Instead of printing 42 ten times, it prints 0 through 9. i was shadowed and was also unused. The compiler will hopefully tell you both these things.
*In C++ constructors and deconstructors are called, of course.