How to decrement several variables in C++in a single line statement? - c++

Edit: I replaced the phrase 'in one line' by 'in a single line statement' since this is what I was looking for
Let's say we have the following variables at hand:
int a = 5;
int b = 9;
Is there a way to compress this ...
a--;
b--;
... into in a single line statement??
The question is not about decrementing multiple variables in a for loop,
since this seems to be a common yet unrelated question.

You probably mean "in a single statement", not just "in a single line".
Then you can use the comma-operator:
(a--,b--);

// use a template
template<class ... Args>
void decr(Args& ... args){
(... , --args);
}
decr(a,b,c);
// or, in C++20, auto
void decr(auto& ... args){
(... , --args);
}

You could just write the statements in one single line, like this :
a--, b--;
(thanks to #Aziz for the improvement with the comma instead of the semicolon)

You can do like :
int a = 5;
int b = 4;
(a -= 1), (b -= 1);
std::cout << a << b;
Output: 43

You can try something like :
#include <iostream>
using namespace std;
main ()
{
int a = 5, b = 9;
a--, b--;
cout << a;
cout << b;
return 0;
}
Output:
48

Related

Despite everything looks fine, values are not swapped

I wanted to write a function to swap two integers. Despite everything looks fine, values are not swapped.
Here is my code:
#include <iostream>
using namespace std;
void mySwap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int a = 5, b = 4;
mySwap(a, b);
cout << a << ' ' << b << endl;
return 0;
}
Output: 5 4
Please, help me understand the reason. Any help is appreciated.
You are copying arguments a and b. Change them to reference.
void mySwap(int & a, int & b)
What you are doing right now is swapping a local Copy of the variables instead of the real variables.
What you need to do, to fix it is to change your function a little bit(just add &, this makes it take a reference of the variables and not create a local copy of them)
void mySwap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
To manipulate with the values passed as arguments in main() directly, use a reference (followed by an ampersand sign &) as shown:
#include <iostream>
void mySwap(int& a, int& b) // using reference here
{
int temp; // remove for alternative option described at the bottom
temp = a; // a = a + b;
a = b; // b = a - b;
b = temp; // a = a - b;
}
int main(void)
{
int a = 5, b = 4;
mySwap(a, b); // passed 5, 4 and original values are manipulated.
std::cout << a << ' ' << b << std::endl;
return 0;
}
As soon as you pass the variables as the function arguments, it'll change originally too.
On the contrary, if you don't use that, the program will just create two local variables that will only be visible inside the function, then even after swapping them, you won't get success.
Another method of swapping between two variables (without a temporary variable):
a = a + b;
b = a - b;
a = a - b;

Function to find largest number

I'm learning C++ through Sololearn. Below is a code to find the largest of two numbers.
#include <iostream>
using namespace std;
int max(int a, int b){
if (a > b) {
return a;
}
return b;
}
int main() {
cout << max(7, 4) << endl;
return 0;
}
Result - 7
But shouldn't it return b also since there's return b in function????
Only one return statement will execute within a function. As soon as the code encounters the first return it will immediately leave the function and no further code will execute.
The answer of CoryKramer says it all.
Still, to avoid the confusion you bumped into, I would prefer:
#include <iostream>
using namespace std;
int max(int a, int b){
if (a > b) {
return a;
}
else {
return b;
}
}
int main() {
cout << max(7, 4) << endl;
return 0;
}
Alternatively you could use:
return a > b ? a : b;
The latter line is a so called 'conditional expression' (or 'conditional operator'). If the phrase before the ? is true, it returns the part between the ? and the :, else it returns the part after the : .
It is explained in detail here.
if (a > b) (7>4) ==> Condition becomes True so return a executed and max function return from there only, its not reach to return b, that's why its not execute return b.
You can use in return a > b ? a : b operator.
Operator return will
terminate the current function and returns the result of the expression to the caller
http://en.cppreference.com/w/cpp/language/return
After you passed the condition
if (a>b)
edited -> thanks to athul
return will evaluate a and put it as result of function.
If a is lesser then b - you will not meet this condition and you will hit
return b;
To understand it, you may add:
cout << max(2, 4) << endl;
cout << max(2, 1) << endl;
into the main section.
PS it is better to use at least codeblocks, which is advised in LearnC++ to enter their examples

Parenthesis after variable name C++

Working with the below source code (it is open source) and I've never seen parenthesis after a variable name. UDefEnergyH is definitely a variable as can be seen in line 1. Can anyone tell me what these parenthesis are doing? Don't really know how to Google this. Thanks.
bins[0] = UDefEnergyH.GetLowEdgeEnergy(size_t(0));
vals[0] = UDefEnergyH(size_t(0)); //Don't know what this does???
sum = vals[0];
for (ii = 1; ii < maxbin; ii++) {
bins[ii] = UDefEnergyH.GetLowEdgeEnergy(size_t(ii));
vals[ii] = UDefEnergyH(size_t(ii)) + vals[ii - 1];
sum = sum + UDefEnergyH(size_t(ii));
}
And it is declared here in the header file:
G4PhysicsOrderedFreeVector UDefEnergyH;
It appears operator() is overloaded for the tyupe of UDefEnerfyH.
One way to do this is this solution
#include <iostream>
using namespace std;
struct MJ {
void GetLowEdgeEnergy(size_t arg) {
cout << "GetLowEdgeEnergy, arg = " << arg << endl;
}
void operator ()(size_t arg) {
cout << "operator (), arg = " << arg << endl;
}
};
int main() {
MJ UDefEnergyH;
UDefEnergyH.GetLowEdgeEnergy(42);
UDefEnergyH(42);
return 0;
}
It seems you are referring to the field in the class G4SPSEneDistribution. Its type is G4PhysicsOrderedFreeVector. And have a look at its members here. As you can see there is operator() overloaded and apparently this is what is called on the second line. It is not very easy to find out what that does, but if you have a look at the comment in the header file for G4PhysicsVector, you will see:
00100 // Returns simply the value in the bin specified by 'binNumber'
00101 // of the dataVector. The boundary check will not be Done. If
00102 // you want this check, use the operator [].
This is what is known as direct initialization, in which it first constructs the object with '0' as an immediate parameter, and then assigns it to the first index of the vals array.

Call by Name/Call by Value

I'm trying to understand this block of code here:
#include <iostream>
using namespace std;
#define mymult(a, b) a*b
inline int mymult1(int a, int b) {return a*b;}
int main() {
cout << "mymult(2+2, 3+3) = " << mymult(2+2, 3+3) << "\n";
cout << "mymult1(2+2, 3+3) = " << mymult1(2+2, 3+3) << "\n";
}
mymult = 11, and mymult1 = 24. I know that '#define's essentially work via call by name, rather than call by value. However, I'm having trouble understanding why the value it returns is 11... and not 24. What causes this?
Option 1:
In the case of:
#define mymult(a, b) a*b
a and b are treated like place holder strings and when you call mymult, the parameters a and b are just copied as they were written. In other words:
mymult(2+2, 3+3) = 2+2*3+3
where a = 2+2, b = 3+3.
Therefore you may call mymult as follows:
mymult( (2+2), (3+3) )
where a = (2+2), b = (3+3).
This will be interpreted as:
mymult( (2+2), (3+3) ) = (2+2)*(3+3)
and return the value of 24 as expected.
Option 2:
If we are allowed to modify the #define statement then an alternative way of doing this is defining it with the parentheses as follows:
#define mymult(a, b) (a)*(b)
This will give the same expected result since a and b will be put directly into the parentheses as they are. In other words:
mymult(2+2, 3+3) = (2+2)*(3+3) = 24
where a = 2+2, b = 3+3.
Option 3:
Stick with the inline function as defined in OP:
inline int mymult(int a, int b) {return a*b;}
Good luck!

Condensing a do-while loop to a #define macro

Consider the following sample code (I actually work with longer binary strings but this is enough to explain the problem):
void enumerateAllSubsets(unsigned char d) {
unsigned char n = 0;
do {
cout<<binaryPrint(n)<<",";
} while ( n = (n - d) & d );
}
The function (due to Knuth) effectively loops through all subsets of a binary string;
For example :
33 = '00100001' in binary and enumerateAllSubsets(33) would produce:
00000000, 00100000, 00000001, 00100001.
I need to write a #define which would make
macroEnumerate(n,33)
cout<<binaryPrint(n)<<",";
behave in a way equivalent to enumerateAllSubsets(33). (well, the order might be rearranged)
Basically i need the ability to perform various operations on subsets of a set.
Doing something similar with for-loops is trivial:
for(int i=0;i < a.size();i++)
foo(a[i]);
can be replaced with:
#define foreach(index,container) for(int index=0;index < container.size();index++)
...
foreach(i,a)
foo(a[i]);
The problem with enumerateAllSubsets() is that the loop body needs to be executed once unconditionally and as a result the do-while cannot be rewritten as for.
I know that the problem can be solved by STL-style templated function and a lambda passed to it (similar to STL for_each function), but some badass #define macro seems like a cleaner solution.
Assuming C++11, define a range object:
#include <iostream>
#include <iterator>
#include <cstdlib>
template <typename T>
class Subsets {
public:
Subsets(T d, T n = 0) : d_(d), n_(n) { }
Subsets begin() const { return *this; }
Subsets end() const { return {0, 0}; }
bool operator!=(Subsets const & i) const { return d_ != i.d_ || n_ != i.n_; }
Subsets & operator++() {
if (!(n_ = (n_ - d_) & d_)) d_ = 0;
return *this;
}
T operator*() const { return n_; }
private:
T d_, n_;
};
template <typename T>
inline Subsets<T> make_subsets(T t) { return Subsets<T>(t); }
int main(int /*argc*/, char * argv[]) {
int d = atoi(argv[1]);
for (auto i : make_subsets(d))
std::cout << i << "\n";
}
I've made it quite general in case you want to work with, e.g., uint64_t.
One option would be to use a for loop that always runs at least once, such as this:
for (bool once = true; once? (once = false, true) : (n = (n - d) & d); )
// loop body
On the first iteration, the once variable gets cleared and the expression evaluates to true, so the loop executes. From that point forward, the actual test-and-step logic controls the loop.
From here, rewriting this to a macro should be a lot easier.
Hope this helps!
You can do a multiline macro that uses an expression, like this:
#define macroenum(n, d, expr ) \
n = 0; \
do { \
(expr); \
} while (n = (n -d) & d) \
; \
int main(int argc, const char* argv[])
{
enumerateAllSubsets(33);
int n;
macroenum(n, 33, cout << n << ",");
}
As others have mentioned this will not be considered very clean by many - amongst other things, it relies on the variable 'n' existing in scope. You may need to wrap expr in another set of parens, but I tested it with g++ and got the same output as enumerateAllSubsets.
It seems like your goal is to be able to do something like enumerateAllSubsets but change the action performed for each iteration.
In C++ you can do this with a function in the header file:
template<typename Func>
inline void enumerateAllSubsets(unsigned char d, Func f)
{
unsigned char n = 0;
do { f(n); } while ( n = (n - d) & d );
}
Sample usage:
enumerateAllSubsets(33, [](auto n) { cout << binaryPrint(n) << ','; } );