C++ Why the parenthesis? - c++

I found this code in a book:
#include <iostream>
using namespace std;
void ChangesAreGood(int *myparam) {
(*myparam) += 10;
cout << "Inside the function:" << endl;
cout << (*myparam) << endl;
}
int main() {
int mynumber = 30;
cout << "Before the function:" << endl;
cout << mynumber << endl;
ChangesAreGood(&mynumber);
cout << "After the function:" << endl;
cout << mynumber << endl;
return 0;
}
It says:
(*myparam) += 10;
What difference would the following produce?
*myparam += 10;

To answer your question:
In your example, there is no difference except in readability.
And, as the comments on this post all suggest, please don't use the parenthesis here...
Interesting other cases
Using a property/method on the dereferenced object
On the other hand, there is a difference if you have something like
*myObject.myPropertyPtr += 10
compared to
(*myPointer).myProperty += 10
The names I chose here tell you what the difference is: the dereference operator * works on whatever is on its right hand side; in the first case the runtime will fetch the contents of myObject.myPropertyPtr, and dereference that, while in the second example it will dereference myPointer, and get myProperty from whatever is found on the object that myPointer points to.
The latter is so common that it even has its own syntax: myPointer->myProperty.
Using the ++ operator rather than +=
Another interesting example, which I thought of after reading another (now deleted) answer to this question, is the difference between these:
*myPointer++
(*myPointer)++
*(myPointer++)
The reason this is more interesting is because since ++ is a call like any other, and particularly doesn't deal with left and right hand side values, it is more ambiguous than your examples with +=. (Of course, they don't always make sense - sometimes you will end up trying to use the ++ operator on an object that doesn't support it - but if we limit our study to ints, this won't be a problem. And it should give you a compiler error anyway...)
Since you caught my curiosity, I conducted a small experiment testing these out. This is what I found out:
*myPointer++ does the same thing as *(myPointer++), i.e. first increment the pointer, then dereference. This shouldn't be so surprising - it is what we'd expect knowing the result of running *myObject.someProperty.
(*myPointer)++ does what you'd expect, i.e. first dereference the pointer, then increment whatever the pointer pointed to (and leave the pointer as is).
Feel free to take a closer look at the code I used to find this out if you want to. Just save it to dereftest.cpp, compile with g++ dereftest.cpp -o dereftest (assuming you have G++ installed) and run with ./dereftest.

Related

References and variable names in C++ - how do they work in regards to memory allocation?

This is a multi part question based on a project I'm currently undertaking. I will try to make it as brief as possible while still fully explaining the question, so sorry if this is a bit long.
When it comes to std::vectors in C++, how exactly do they work with variables? For example, if I have the following code:
int myInt = 4;
std::vector<int> myIntVector;
myIntVector.push_back(myInt);
what happens? Does that area of memory inside myIntVector now have the same value of data stored inside myInt at the time of adding, but still completely separate them? Does the area of memory where myInt is stored get physically moved into a designated area inside of the memory of myIntVector?
Assuming I was correct on the last statement, why would std::cout << myInt still correctly print 4, assuming it was not changed, while std::cout << myIntVector[0] also prints out 4?
Now, for what prompted the question: the #define directive. I was experimenting with this for my project, and noticed something interesting. I used #define GET_NAME(variable) (#variable), which returns the name of the inputted variable as a character array. If I were to have the following code:
#define GET_NAME(variable) (#variable)
int myInt = 4;
std::vector<int> myIntVector;
myIntVector.push_back(myInt);
std::cout << GET_NAME(myInt) << "\n";
std::cout << GET_NAME(myIntVector[0]);
I would receive the following output:
myInt
myIntVector[0]
Why? Assuming the first statement from question 1 is correct, this is the expected output, but then we circle back to question 2. Assuming the second statement from question 2 is correct, this is the unintended output, as myInt or myIntVector[0] should be returned twice.
Thanks in advance!
When it comes to std::vectors in C++, how exactly do they work with variables?
All STL containers just copy values by default. So when you pass an int variable, it gets copied and the copy exist completely independently from the original value
why would std::cout << myInt still correctly print 4, assuming it was not changed, while std::cout << myIntVector[0] also prints out 4?
These are two different values, both equal to 4
If I were to have the following code, I would receive the following output. Why?
The macros just manipulate the text, and don't do anything fancy in your code. This statement:
std::cout << GET_NAME(myInt) << "\n";
Just turns into this under the macro:
std::cout << "myInt" << "\n";

Why does cout.precision() affect the whole stream?

I feel I'm asking a very basic question, but I haven't been able to find an answer here or in Google. I recall we were taught this at school, but alas it has vanished over years.
Why does cout.precision() (std::ios_base::precision()) affect the whole stream when called in the middle of the output list? I know the rule that std::setprecision() should be used to change precision on the fly, and that cout.precision() is going to spoil the output with the value it returns. But what is the mechanics of this? Is it due to buffering? The manuals state these "do the same thing", but empirically I can see it's not entirely true.
MCVE:
const double test = 1.2345;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << test << endl << cout.precision(3) << test << endl;
// Output:
// 1.234
// 21.234
// after the same init
cout.precision(2);
cout << test << endl << setprecision(3) << test << endl;
// Output
// 1.23
// 1.234
Is this "implementation specific / not defined by the standard"?
Feel free to mark this as duplicate, for I haven't been able to find it on SO.
The order of function argument evaluation is unspecified. When you call std::cout.precision(n) the precision of std::cout' is set at the point this call is evaluated. In your expression
cout << test << endl << cout.precision(3) << test << endl;
the cout.precision(3) is, apparently, called first thing which the compiler is entirely allowed to do. Remember that the compiler considers the above statement equivalent to
std::cout.operator<<(test)
.operator<<(std::endl)
.operator<<(std::cout.preision(3))
.operator<<(test)
.operator<< (std::endl);
Practically, it seems for your compiler function arguments are evaluated right to left. Only then the different shift operators are executed. As a result, the precision gets changed before the output is done.
The use of manipulators like std::setprecision(n) avoids relying on the order subexpressions are evaluated: the temporary created from std::setprecision(n) is created whenever it is. The effect is then applied when the appropriate shift operator is called. Since the shift operators have to be called in the appropriate order, the use of the manipulator happens at a known place.
The exact time when cout.precision(3) is evaluated in your first example is not defined, because its value serves as an argument for a function call. OTOH with the second example, the time when setprecision(3) is inserted to the stream is very well defined - i.e. after endl is inserted and before test (2nd time). Therefor the first version will not produce reliable results (what you get may be different on different implementations), but the second version will.
See this question for a more detailed explanation. (The question there doesn't use operators, but the principle is the same - calling a member function on the return value of another function.)

C++ - Value of local non-initialized variables

I was writing a simple program to test how the scope of variables works, but I'm obtaining unexpected results, so I was hoping you could give me an hand to understand them.
I compiled this code
#include<iostream>
using namespace std;
void myFunction1()
{
int e;
cout << e << endl;
e++;
cout << e << endl<<endl;
}
int main()
{
cout << "MAIN" << endl;
int a,b,c,d;
cout << "a= " << a << endl;
cout << "b= " << b << endl;
cout << "c= " << c << endl;
cout << "d= " << d << endl<<endl;
cout << "MY_FUNC" << endl;
myFunction1();
myFunction1();
myFunction1();
}
and obtained this output
MAIN
a= -1617852976
b= 32767
c= 0
d= 0
MY_FUNC
32675
32676
32676
32677
32677
32678
So, there are two things I really don't understand
1) In the main() function I'm creating 4 int variables (a,b,c,d) WITHOUT initializing them, so I expect them to assume a different value each time I run the code. Strange thing is, the first variable (a) is always different, while the others always assume the same values (b=32767, c=d=0)
2) The function output is even stranger to me.
Again, I'm creating a variable e without initializing it, so the first time it assumes a random value (in the example, e=32675).....then, I increase it by one, so that it prints 32675 and 32676, and that sounds right.
But how come the second time I call the function, e keeps the previous value (32676)? I thought e was created each time I call myFunction1() and deleted at the end of the function, so that e assumed a different random value each time (since I don't initialize it). Why is the value of e stored even if the variable goes out of scope?
Uninitialized primitive values are simply not defined. They can have any value.
It is an undefined behavior. That's why it doesn't make any sense to analyze the behavior of this program.
In the main() function I'm creating 4 int variables (a,b,c,d) WITHOUT initializing them, so I expect them to assume a different value each time I run the code
This assumption is flawed. They may have a different value each time you run the code, but they may not. Anything could happen. The point of UB is that you should drop all your assumptions.
But how come the second time I call the function, e keeps the previous value (32676)? I thought e was created each time I call myFunction1() and deleted at the end of the function, so that e assumed a different random value each time (since I don't initialize it)
It does. If you replace "random" for the more correct "arbitrary", then the results you're seeing fit that pattern just fine.
It's just pure luck, and comes down to the state you're leaving unclaimed memory in at each stage of your program's execution.
A good way to help you understand this is to explain in terms of memory allocation.
When you run a program, a certain amount of memory that is not used is assigned to your variable.
Computers are lazy, the best way to delete a data is to forget where it is stored. When you assign a chunk of memory to a variable, you are telling the computer to remember where that certain data belongs to.
If it so happens that it was used prior to you assigning the memory to the variable, it will simply read (let's say 4 bytes for a common machine) and get the data from that location.
Hope that this helps =)

Called a function with "cout" statement inside a "cout" statement

I came across this rather vague behavior when messing around with code , here's the example :
#include <iostream>
using namespace std;
int print(void);
int main(void)
{
cout << "The Lucky " << print() << endl; //This line
return 0;
}
int print(void)
{
cout << "No : ";
return 3;
}
In my code, the statement with comment //This lineis supposed to print out
The Lucky No : 3, but instead it was printed No : The Lucky 3. What causes this behavior? Does this have to do with C++ standard or its behavior vary from one compiler to another?
The order of evaluation of arguments to a function is unspecified. Your line looks like this to the compiler:
operator<<(operator<<(operator<<(cout, "The Lucky "), print()), endl);
The primary call in the statement is the one with endl as an argument. It is unspecified whether the second argument, endl, is evaluated first or the larger sub-expression:
operator<<(operator<<(cout, "The Lucky "), print())
And breaking that one down, it is unspecified whether the function print() is called first, or the sub-expression:
operator<<(cout, "The Lucky ")
So, to answer your question:
What causes this behavior? Does this has to do with C++ standard or its behavior vary from one compiler to another?
It could vary from compiler to compiler.
Let's call the operator << simply operator .
Now we can write
cout << "The Lucky"
as
operator(cout, "The Lucky")
The result of this operation is cout, and it is passed to next <<, so we can write
operator(operator(cout, "The Lucky"), print() )
It is a function invocation with two parameters, and the standard doesn't say anything about the order of their evaluation.
So with some compilers you really may get
The Lucky No : 3
In my compiler No: The Lucky 3 is the output.... it means that its behaviour varies from compiler to compiler.

Strange behavior when trying hacking a constant in C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Modifying a const through a non-const pointer
I'm studying C++, and very interesting about pointers. And I tried to change value of a constant value (my teacher called it backdoor, please clarify if I'm wrong) like this:
const int i = 0;
const int* pi = &i;
int hackingAddress = (int)pi;
int *hackingPointer = (int*)pi;
*hackingPointer = 1;
cout << "Address:\t" << &i << "\t" << hackingPointer << endl;
cout << "Value: \t" << i << "\t\t" << *hackingPointer << endl;
system("PAUSE");
return 0;
However, the result is very strange. Although the two addresses are the same, the values are different.
How is my code executed? And where is 0 and 1 value is stored exactly?
You've discovered a little thing that C++ developers call undefined behavior. You told the compiler that "i is a constant with the value 0". So when you ask the compiler for the value of i, it tells you that it is 0.
Mucking around with trying to change the value of a constant violates the assumptions made by the compiler (that constants are going to be, well, constant), and so, the compiler is going to generate invalid or inconsistent code.
There are a lot of situations in C++ where it is possible to do something without the compiler catching it as an error, but the result is undefined. And if you do that, then you get results like what you're seeing. The compiler does something weird and unexpected.
Oh, and if your teacher is trying to teach you anything from an example such as this, he's wrong, and you should be very scared.
The only guarantee you get from code like this is this:
the compiler can do literally anything it likes
When you write code, you have an implicit contract with the compiler:
"If I write well-defined C++ code, then you convert it into an executable with the same effects as described by the C++ standard".
When you do something like this, you violate the contract. And then the compiler isn't obliged to follow it either. If you give the compiler code that is not well-defined according to the C++ standard, then it can't, and isn't going to, create an executable which does as the C++ standard specifies.
It seems, that compiler has optimized (inlined int const value)
cout << "Value: \t" << i << "\t\t" << *hackingPointer << endl;
to
cout << "Value: \t" << 0 << "\t\t" << *(0x0044ff28) << endl;
Anyway, you have still succeeded to change value of memory where i is stored. But do not try this at home :-)
It is not permitted to change the values of a constant, in fact it's undefined behaviour so your program could do anything as a result.
In this instance it looks like your compiler optimised the read away at compile time because it knew the value is fixed. Lots of implementations might just crash when you try and change it, but you cannot and should not bet or rely upon the result of any undefined behaviour ever.