The arrays are passed by reference. Any changes made to the array within the function changeArray will be observed in the calling scope (main function here).
However the codes below print 0 1 in the 1st cout, and print 2 in the 2nd "cout". What I don't understand is that why the first cout prints the original value of array[0]=1 instead of the changed value of array[0]=2?
Thanks a lot.
#include <iostream>
using namespace std;
int changeArray(int array[]) {
array[0]=2*array[0];
return 0;
}
int main() {
int array[]={1,2,3,4};
cout << changeArray(array) << " " << array[0] << endl;
cout << array[0] << endl;
return 0;
}
To make sure that the compiler doesn't reorder the execution:
cout << array[0] << endl;
changeArray(array);
cout << array[0] << endl;
This prints 1 and then 2.
The C++ compiler is allowed to optimize the code by reordering the execution of code within a single expression (e.g. cout << changeArray(array) << " " << array[0] << endl). To avoid that, and to make sure changeArray gets called first, you need to split your expression to separate statements, e.g. by using the semicolon (;). Everything before the semicolon gets executed before anything after the semicolon can start.
Related
I have a recursive display function, meant to go through the values of array b and print the details. My function is successful in looping the correct amount of times, but only prints out the value at index 0. For example, if I have 3 books, it prints out the first book 3 times and is not going to the other values. I am a beginner programmer and I believe I am missing something very simple or obvious, but any help is appreciated.
void displayBooks(int n)
{
// Write the code below
if (n >= currentCount) {
return;
}
else {
cout << "Name: " << b->getName() << "\n";
cout << "Name of Book Author: " << b->getAuthor() << "\n";
cout << "Publication Year: " << b->getYearOfPublication() << "\n";
cout << "ID: " << b->getID() << "\n";
displayBooks(n + 1);
}
}
This is the function itself, however I can't show the complete program since it is a lot of code with multiple files. When the function is first called as displayBooks(0) in a switch case.
I believe that you are not printing out each index of the "b" variable you need to access the index of each one. You need to have b as an array of pointers then access the index of that variable like b[n]->someProperty();
You can create the array like this:
Obj* b[HOWMANY];
I have set the size of the character array to 2 bytes. But it can hold more than 2 bytes. how is it possible?
#include<iostream>
int main() {
char a[2];
std::cout << "enter the name" << std::endl;
std::cin >> a;
std::cout << "the name is " << a << std::endl;
system("pause");
return 0;
}
I am expecting some other output
but the output is .....
enter the name
Sami
the name is Sami
What happens is that you are effectively writing past the end of the allocated memory.
C++ doesn't check that the input provided fits intothe variable a so you are actually writing out of the bounds of the memory allocated to your program, resulting in Undefined Behaviour.
Your program seems to work, but you have actually no guarantees that it will behave as you wish.
Don't use a fixed size array of char, but use std::string instead.
Here is a fixed code example.
#include<iostream>
#include<string>
int main() {
std::string a;
std::cout << "enter the name" << std::endl;
std::getline(std::cin, a);
std::cout << "the name is " << a << std::endl;
system("pause");
return 0;
}
So when I have this function, and I print it to the console via multiple statements, I get the expected results:
0
1
But when I print the function out through just one cout statement on the same line, I get:
3 2
(This is after the initial 0 and 1 that were previously printed)
Why does it print backwards?
#include "stdafx.h"
#include <iostream>
using namespace std;
int addOne()
{
static int s_num = -1;
return ++s_num;
}
int main()
{
cout << addOne() << "\n";
cout << addOne() << "\n";
cout << addOne() << " " << addOne() << "\n";
return 0;
}
You are actually stumbling on unspecified behavior. In this context, and any other such context where the operators are of the same precedence, the function calls can be evaluated in any order. In this case, the compiler chose to evaluate the second function call before the first, but other compilers might do it differently.
I'm using this code to output nodes of a huffman tree to a text file with a certain formatting. All the node outputs within the if block run as expected, but the first output in the else block is missing the '0' fill character after the "L:". It should output "L:076" but instead is outputting "L: 76". The cout looks correct but the text file isn't. All future loops through the else block output like they should, it's only the first loop that is missing the fill character. Here's a picture of my output
void preOrder(node* tree, std::ofstream& of) {
if (tree->label > 0) {
of << "I:" << tree->label << " ";
}
else {
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << int(tree->ch) << std::endl;
of << "L:";
of << of.fill('0');
of << std::right;
of << int(tree->ch);
of << " ";
return;
}
preOrder(tree->left, of);
preOrder(tree->right, of);
}
From cppreference.com:
The second form (2) sets fillch as the new fill character and returns the fill character used before the call.
"The second form" is the non-const version, that applies here. So my guess (I never used fill myself and I cannot compile your code as it is) would be that the call is correctly applied and then you put the old fill character (blank space presumably) to the stream, because you do:
of << of.fill('0');
Also, I noticed that you dont set the width of of.
Because you're hiding something naughty from us.
#include <iostream>
int main()
{
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << 3 << std::endl;
return 0;
}
Outputs 003 (live example).
Please provide an MCVE and I'll edit my answer to help you.
Please look at the code snippet below - I have declared 3 functions (i.e. 1 passing an int and the others passing reference to an int). After executing the program I found that the value of "count" variable after calling function (tripleByReference) has not been changed to reflect its triple (count is still equal to 5). However calling function (tripleByReferenceVoid) modifies the variable but this is due to the fact that changes occurred directly to the variable (count).
I understand that with pass by reference, the caller gives the called function the ability to access the caller's data directly and modify it but that could not be achieved by passing the variable to function (tripleByReference) - Please help me to understand this.
#include <iostream>
using namespace std;
/* function Prototypes */
int tripleByValue(int);
int tripleByReference(int &);
void tripleByReferenceVoid(int &);
int main(void)
{
int count = 5;
//call by value
cout << "Value of count before passing by value is: " << count << endl;
cout << "Passing " << count << " by value, output is: "
<< tripleByValue(count) << endl;
cout << "Value of count after passing by value is: " << count << endl;
//call by reference - using int tripleByReference
cout << "\n\nValue of count before passing by reference is: " << count << endl;
cout << "Passing " << count << " by reference, output is: "
<< tripleByReference(count) << endl;
cout << "Value of count after passing by reference is: " << count << endl;
//call by reference - using void tripleByReference
tripleByReferenceVoid(count);
cout << "\n\nValue of count after passing by reference is: " << count << endl;
cout << endl;
system("PAUSE");
return 0;
}//end main
int tripleByValue (int count) {
int result = count * count * count;
return result;
}//end tirpleByValue function
int tripleByReference(int &count) {
int result = count * count * count;
return result; //perform calcs
}//end tripleByReference function
void tripleByReferenceVoid(int &count) {
count *= count * count;
}//end tripleByReference function
Thank you.
tripleByReference doesn't change the value of count because you never assign to it. You are returning the value instead.
tripleByReferenceVoid is different. You are assigning to it (count *= ...) and that is why these changes are reflected.
In your function tripleByReference you are not even attempting to modify the value of count, while in your function tripleByReferenceVoid you are explicitly modifying count. Hence the obvious and expected effect: the latter function modifies count, the former doesn't. I.e. these functions do exactly what and only what you explicitly and consciously asked them to do.
Questions like this one is difficult to answer because it is virtually impossible to understand what made you to ask it. You seem to be puzzled by the fact that the behavior of these two functions is different. But why does it puzzle you, when you yourself explicitly wrote them to be different in that specific regard?