I need to understand how this code works:
#define foo1( a ) (a * a) // How does this work?
inline int foo2( int a ) { return (a * a); }
int goo1( int x ) { return foo1(foo2(x)); }
int goo2( int& x ) { return x = foo2(foo1(x)); }
int goo3( int& x, int y ) { return foo2(foo1(y + 1)); }
void goo4( int& x, int y ) { x = foo1(foo2(y + 1)); }
int main(){
int i = 2, j = 1, a = 2+3;
cout << "foo1 = " << foo1( 1+2 ) << "\n"; // How does this work?
cout << "foo2 = " << foo2( 2 + 1 ) << "\n";
cout << "goo1 = " << goo1( i ) << "\n";
cout << "goo2 = " << goo2( j ) << "\n";
cout << "goo3 = " << goo3( i, j ) << "\n"; // How does this work?
goo4( i, j );
cout << " i = " << i << " j = " << j << "\n";
}
But I do not seem to be able understand the behaviour of this function:
#define foo1( a ) (a * a)
and hence I don't understand the output of these two function calls:
foo1( 1+2 )
goo3( i, j )
This is the output of the program:
foo1 = 5
foo2 = 9
goo1 = 16
goo2 = 1
goo3 = 9
i = 16 j = 1
I can't see why foo1 is not behaving like foo2. Would someone explain to me how this #define macro works?
NOTE: I must not change the code, I am only trying to understand the output.
Well, it's really simple.
foo1( 1 + 2 )
will turn into:
( 1 + 2 * 1 + 2 )
which is actually:
1 + 2 + 2 = 5
This is how macros work.
Macros are not functions.
Macros do TEXT replacement. So when you have
#define foo1( a ) (a * a)
any instance of foo1( ... ) with anything between then parenthesis will be expanded AS TEXT, not as an expression. So when you have foo1( 1 + 2 ) it turns into ( 1 + 2 * 1 + 2 )
Macro is not a function.
The compiler will expand all macros and then compile it. To see the expanded code, you can use the following command using -E option in gcc:
gcc -E <source code> -o <preprocessed file name>
Or in Visual C++, under Configuration Properties->C/C++->Preprocessor, set "Generate Preprocessed File".
BTW, your macro is problematic.
You should use
#define foo1( a ) ((a) * (a))
instead of
#define foo1( a ) (a * a)
The difference is, the foo1 defined by #define is NOT a function, while foo2 is.
In compilation process, the compiler will replace the foo1(parameter) keyword in your code with (parameter * parameter).
Meaning,
cout << "foo1 = " << foo1( 1+2 ) << "\n"; // How does this work?
will be replaced by the following code,
cout << "foo1 = " << ( 1+2 * 1+2 ) << "\n"; // How does this work?
(Because the parameter here is 1+2, instead of 3.)
The result is 1+2 * 1+2, which is 5.
Now let look at foo2, since it is an inline function, the compiler will not replace it. When your code is compiled into an executable file, and the executable file is executed, the 2 + 1 expression will be calculated first, and the result, 3, will then be passed to foo2().
In conclusion, the difference really lies in the compilation of your code. You may need more knowledge on what happens there.
Related
Is there a way to make macro using #define, which will take two arguments and "return" string in specified format with values of given arguments?
Something like this:
#define MACRO( x, y ) ( "OK ", x, " ", y, " \a\b" ) // i know this doesn't work
int main ()
{
int a = 3,
b = -1;
std::cout << MACRO( a, b ) << std::endl; // this should print following string: "OK 3 -1 \a\b"
return 0;
}
I can define a macros which print only fixed variable count, for example:
#define PRINT_PARAMS(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";
// using:
int varI = 5;
PRINT_PARAMS( varI );
// output:
test: varI = 5
How to define a macros which will do something like that:
PRINT_PARAMS( varI1, strValue2, floatValue3, doubleValue4 );
// output:
varI1 = 5, strValue2 = some string, floatValue3 = 3.403f, ....
I mean any number of input parameters.
#include <string>
#include <iostream>
//"for each" macro iterations
#define FE_1(Y, X) Y(X)
#define FE_2(Y, X, ...) Y(X)FE_1(Y, __VA_ARGS__)
#define FE_3(Y, X, ...) Y(X)FE_2(Y, __VA_ARGS__)
#define FE_4(Y, X, ...) Y(X)FE_3(Y, __VA_ARGS__)
#define FE_5(Y, X, ...) Y(X)FE_4(Y, __VA_ARGS__)
//... repeat as needed
//the "for each" call
#define GET_MACRO(_1,_2,_3,_4,_5,NAME,...) NAME
#define FOR_EACH(action,...) \
GET_MACRO(__VA_ARGS__,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)
//function to print a single
#define PRINT_SINGLE(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";
//function to print n amount
#define PRINT_PARAMS(...) FOR_EACH(PRINT_SINGLE,__VA_ARGS__)
int main(){
std::string s1 = "hello";
float f = 3.14;
int i = 42;
PRINT_PARAMS(s1,f,i)
}
Don't have a compiler to hand but was wondering if the following variadic macro would work (or at least help give you an idea.)
#define PRINT_PARAMS(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";
#define PRINT_PARAMS(a, ...) { PRINT_PARAMS((a)); PRINT_PARAMS(__VA_ARGS__); }
I am trying to calculate the final digit of a 13 digit ISBN using the first 12 digits using C++. I feel like my code should be correct but I have a feeling the formula I'm using may be wrong.
The formula is:
10 - (d0 + d1 * 3 + d2 + d3 * 3 + d4 + d5 * 3 + d6 + d7 * 3 + d8 + d9 * 3 + d10 + d11 * 3) % 10
Here's what I have:
#include <cstring>
#include <iostream>
int main() {
int weightedSum = 0;
int checksum = 0;
int i; //for loop decrement
int mul = 3;
const int LENGTH = 12;
char ISBNinput[LENGTH];
std::cout << "Enter first 12 digits of ISBN: "; //ask user for input
std::cin >> ISBNinput; //stores input into ISBNinput
std::cout << std::endl;
for (i = 0; i < strlen(ISBNinput); i++) {
weightedSum += (ISBNinput[i] % 12) * mul;
if (mul == 3) {
mul = 1;
} else {
mul = 3;
}
}//close for loop
checksum = weightedSum % 10; //calculates checksum from weightedSum
std::cout << checksum << std::endl; //prints checksum with new line for format
return 0;
}
For example:
978007063546 should return 3
and
978032133487 should return 9
Thank you for any help.
Here's how I go about this.
First, let's decide how we're going to test this. I'll assume that we've written the function, and that it gives the correct output. So I pick up a couple of books off my desk, and test that it works for them:
#include <iostream>
int main()
{
std::cout << "Book 1 - expect 3, got " << checksum("978032114653") << std::endl;
std::cout << "Book 2 - expect 0, got " << checksum("978020163361") << std::endl;
}
Of course, when we try to compile that, we get an error. So create the function, before main():
char checksum(const char *s)
{
return '1';
}
Now it compiles, but the result is always 1, but now we can start to fill in the body. Let's start with some smaller examples, that we can calculate by hand; add these at the beginning of main():
std::cout << "1 digit - expect 4, got " << checksum("6") << std::endl;
Now let's get this one working - this gives us conversion from character to digit and back, at least:
char checksum(const char *s)
{
int digit = *s - '0';
return '0' + 10 - digit;
}
Let's try 2 digits:
std::cout << "1 digit - expect 6, got " << checksum("11") << std::endl;
And now our test fails again. So add some more processing, to make this pass (and not break the single-digit test):
char checksum(const char *s)
{
int sum = 0;
int digit = *s - '0';
sum += digit;
++s;
if (*s) {
digit = *s - '0';
sum += 3 * digit;
}
return '0' + (10 - sum)%10;
}
We're probably ready to make this into a loop now. Once that's passed, we no longer need the short tests, and I have:
#include <iostream>
char checksum(const char *s)
{
int sum = 0;
for (int mul = 1; *s; ++s) {
int digit = *s - '0';
sum += mul * digit;
mul = 4 - mul;
}
return '0' + (1000 - sum)%10;
}
int test(const char *name, char expected, const char *input)
{
char actual = checksum(input);
if (actual == expected) {
std::cout << "PASS: " << name << ": "
<< input << " => " << actual
<< std::endl;
return 0;
} else {
std::cout << "FAIL: " << name << ": "
<< input << " => " << actual
<< " - expected " << expected
<< std::endl;
return 1;
}
}
int main()
{
int failures = 0;
failures += test("Book 1", '3', "978032114653");
failures += test("Book 2", '0', "978020163361");
return failures > 0;
}
I factored out the actual checking into a function here, so we can keep count of failures, and exit with the appropriate status, but everything else is as I described above.
You'll want to add a few more test cases - in particular, make sure the function correctly returns the extreme values 0 and 9 when it should.
There is one clear bug in your code: you are not allocating enough space in for ISBNinput. You should make it one character longer:
const int LENGTH = 13;
The reason for this is that that character-array strings are terminated with an extra null character. You might be lucky and the next byte in memory could sometimes happen to be a null byte, in which case the program would still work sometimes.
If you run the program with valgrind or a similar memory checker you are likely to see an error as the program access memory beyond what was allocated on the stack.
Also I think there is another bug. I think that mul should be initialized to 1.
By the way, this code is very fragile, depending on you entering no more than 12 characters, all of which are assumed to be digits. It might be OK as a quick hack for a proof-of-concept, but should not be used in any real program.
I'm running the following code:
double Scos [61][61][61] = {0};
double kdotr;
int ik;
int howmany [34] = {0};
auto Fs_ = initializer_list<int>({0});
copy(Fs_.begin(), Fs_.end(), Fs);
for ( size_t z=0; z<5; ++z )
{
for ( size_t y=0; y<5; ++y )
{
for ( size_t x=0; x<10; ++x )
{
for ( int k1=0; k1<=60; ++k1 )
{
for ( int k2=0; k2<=60; ++k2 )
{
for ( int k3=0; k3<=60; ++k3 )
{
int i = x+y*10+z*50;
kdotr = (double)dQ*( (k1-30)*(x_[i][0]-x) + (k2-30)*(x_[i][1]-y) + (k3-30)*(x_[i][2]-z) );
if ( isnan(kdotr) )
cout << "kdotr " << k1 << " " << k2 << " " << k3 << endl;
Scos[k1][k2][k3] += (double)cos(kdotr);
if ( isnan(Scos[k1][k2][k3]) )
cout << "Scos " << k1 << " " << k2 << " " << k3 << endl;
}
}
}
}
}
}
for ( int k1=0; k1<=60; ++k1 )
{
for ( int k2=0; k2<=60; ++k2 )
{
for ( int k3=0; k3<=60; ++k3 )
{
double k = (double)dQ*sqrt( pow((k1-30),2) + pow((k2-30),2) + pow((k3-30),2) );
ik = round(k/0.1);
Fs[ik] += Scos[k1][k2][k3];
if ( isnan(Fs[ik]) )
cout << "Fs[ik] " << k1 << " " << k2 << " " << k3 << endl;
++howmany[ik];
}
}
}
At the beginning there are just some declarations and initializations (array Fs was already declared somewhere else, together with dQ and x_).
I put calls to isnan because the code strangely returns some NaNs. At first, I believed the problem was with kdotr going to infinity, which would have been argument of cos; however, the code never fails at Scos, but at some Fs[ik]. This does not make sense to me, since Fs comes from a simple sum (and it is initialized to 0).
Has ever happened to you to obtain NaN after a sum between finite terms in C++?
This sort of problem is ALWAYS caused by some input to a calculation either being "invalid" (leading to the FPU generating a NaN as the result) or using "NaN" as an input in itself.
In this case, having a quick scan through the operations you do, it seems like there are only operations that don't generate NaN based on (for example) negative inputs [like sqrt or log would do], so my thinking is that one or more of your inputs are reading uninitialized (or incorrectly initialized) data.
I would start by checking that all the components of:
x_[i][0]-x) + (k2-30)*(x_[i][1]-y) + (k3-30)*(x_[i][2]-z
are not NaN. In particular x_[i][0,1,2].
Since your code is not a complete piece of exectutable code, and some variable's initialization isn't even in the code-snippet, it will be impossible for anyone here to give you a precise answer to where in your code it is going wrong.
Ok, I make the code work without NaNs.
As some commenters pointed out, there could be problems with the initializations. In fact, instead of using directly Fs (which is a member of a greater class - this code itself is part of a method), I stored the sums of cosines in a temporary array Fs_, declared and initialized inside the method (e.g. like Scos): now there are no NaNs anymore.
Could you like to tell how to split clauses of unsat cores?
And here is question 2 regarding after found out unsat cores, I will try to seek again.
Would you like to tell how to do this?
Thank you very much.
How to split the clauses as below
`and` (`or` (`<=_int` 1002 x1) (`<=_int` 1000 x1)) (`and` (`or` (`<=_int` 0 (`+_int` x2 (`*_int` -1003 x1))) (`<=_int` 0 (`+_int` x2 (`*_int` -1230 x1)))) (`and` (`or` (`<=_int` 0 (`+_int` x3 (`*_int` -1999 x2)))
Regarding to the question 2,
cout<<s.check(3,assumptions)<<endl;
expr_vector core = s.unsat_core();
................
expr assumptions2[2] = {p1,p3};
cout<<"check next"<<s.check(2,assumptions2)<<endl;
expr_vector core1 = s.unsat_core();
for(unsigned int k=0;k<core1.size();++k){
cout<<"New core size "<<k<<endl;
cout<<"New unsat core "<<core1[k]<<endl;
}
calling the unsat core function again, it cannot give the unsat cores again.
Thank you very much.
I'm not sure if I understood your question. It seems you have an assertion of the form (and c1 (and c2 c3)), and you want to track c1, c2 and c3 individually.
In Z3, we use answer literals to track assertions. An answer literal is essentially a fresh Boolean that is used to track an assertion. That is, whether the assertion was used (by Z3) to show unsatisfiability of the whole set of assertions or not. For example, if we want to track assertion F, we create a fresh Boolean variable p and assert p implies F. Then, we provide p as an argument for the check method.
If F is a big conjunction and we want to track its elements individually, we should extract its elements and create an answer literal for each one of them. Here is the complete example that does the trick. You can test it by including it in the example.cpp file that is included in the Z3 distribution. Note that you have to include #include<vector>.
/**
\brief Unsat core example 2
*/
void unsat_core_example2() {
std::cout << "unsat core example 2\n";
context c;
// The answer literal mechanism, described in the previous example,
// tracks assertions. An assertion can be a complicated
// formula containing containing the conjunction of many subformulas.
expr p1 = c.bool_const("p1");
expr x = c.int_const("x");
expr y = c.int_const("y");
solver s(c);
expr F = x > 10 && y > x && y < 5 && y > 0;
s.add(implies(p1, F));
expr assumptions[1] = { p1 };
std::cout << s.check(1, assumptions) << "\n";
expr_vector core = s.unsat_core();
std::cout << core << "\n";
std::cout << "size: " << core.size() << "\n";
for (unsigned i = 0; i < core.size(); i++) {
std::cout << core[i] << "\n";
}
// The core is not very informative, since p1 is tracking the formula F
// that is a conjunction of subformulas.
// Now, we use the following piece of code to break this conjunction
// into individual subformulas. First, we flat the conjunctions by
// using the method simplify.
std::vector<expr> qs; // auxiliary vector used to store new answer literals.
assert(F.is_app()); // I'm assuming F is an application.
if (F.decl().decl_kind() == Z3_OP_AND) {
// F is a conjunction
std::cout << "F num. args (before simplify): " << F.num_args() << "\n";
F = F.simplify();
std::cout << "F num. args (after simplify): " << F.num_args() << "\n";
for (unsigned i = 0; i < F.num_args(); i++) {
std::cout << "Creating answer literal q" << i << " for " << F.arg(i) << "\n";
std::stringstream qname; qname << "q" << i;
expr qi = c.bool_const(qname.str().c_str()); // create a new answer literal
s.add(implies(qi, F.arg(i)));
qs.push_back(qi);
}
}
// The solver s already contains p1 => F
// To disable F, we add (not p1) as an additional assumption
qs.push_back(!p1);
std::cout << s.check(qs.size(), &qs[0]) << "\n";
expr_vector core2 = s.unsat_core();
std::cout << core2 << "\n";
std::cout << "size: " << core2.size() << "\n";
for (unsigned i = 0; i < core2.size(); i++) {
std::cout << core2[i] << "\n";
}
}