Declaration of function in c++ - c++

I wrote this code and I don't know what to do to change that. This code I want to use in my Raspberry pi with sonars - hc sr 04 to measure a distance. Please do you know how to fix my code? :) before this I wrote a code for-example. This is my real code. So please check it again :) thanks!
int zmeratSonar1() {
int smer = 0;
printf("meram sonar1");
digitalWrite(TRIGsonar1, HIGH);
delayMicroseconds(20);
digitalWrite(TRIGsonar1, LOW);
while (digitalRead(ECHOsonar1)==LOW);
long zaciatok = micros();
while (digitalRead(ECHOsonar1)==HIGH);
long cas = micros() - zaciatok;
int vzdialenost = cas/58;
if(vzdialenost < 100) {
smer = zmeratSonar28(); // <----here is my problem
}
else if(vzdialenost > 100) {
zmeratSonar1();
}
return smer;
}
int zmeratSonar28(){
int smer = 0;
printf("meram sonare 2 a 8");
//------------SONAR 2---------------------
digitalWrite(TRIGsonar2, HIGH);
delayMicroseconds(20);
digitalWrite(TRIGsonar2, LOW);
while (digitalRead(ECHOsonar2)==LOW);
long startTime2 = micros();
while (digitalRead(ECHOsonar2)==HIGH);
long travelTime2 = micros() - startTime2;
int distance2 = travelTime2/58;
//------------SONAR 8----------------------
digitalWrite(TRIGsonar8, HIGH);
delayMicroseconds(20);
digitalWrite(TRIGsonar8, LOW);
while (digitalRead(ECHOsonar8)==LOW);
long startTime8 = micros();
while (digitalRead(ECHOsonar8)==HIGH);
long travelTime8 = micros() - startTime8;
int distance8 = travelTime8/58;
//porovnanie vzdialenosti
if(distance2 > 100 || distance8 > 100) {
if(distance2 > distance8) {
smer = 2;
}
else {
smer = 8;
}
}
else{
smer = 0;
}
return smer;
}

You are using the function sum before you have declared it. You could either move the function sum above the use, or you could forward declare it:
int sum(); // Forward declared
int number = 0;
int a() {
for(int i = 0; i < 20; i++) {
if((i % 2) == 1) {
number = sum();
}
}
return number;
}
int sum() {
number = number + 100;
return number;
}
Further explanation of the this problem, can be found elsewhere on Stack Overflow, such as the answers to this question: Why do functions need to be declared before they are used?
Note: I never thoroughly tested your code, which I guess you never did either, so as LogicStuff pointed out it didn't even compile, I've made a few changes to make the code compile, as few changes as possible so that the original code should still be visible from it. Thanks for pointing it out LogicStuff.

I suppose your problem is that you have a compilation error. You use sum in place where it is not yet visible. Either move sum above a(), or forward declare it with int sum(); above a().
Another problem is that:
if(i % 2 = 1) {
should be:
if((i % 2) == 1) {
^~~~~ !!
Whoo, I found third problem :)
You try to use variable number inside int sum() which is declared inside of a(), you simply cannot do it. You should pass number to sum by reference (no need for return value, you return it in number parameter):
void sum(int& number) {
and call it:
sum(number); // this is in place of `number = sum();`
in a()

There are a number of errors in your code which will cause compiler errors:
If you're using the sum() function in int a(), then you need to forward-declare it.
int sum();
int add() {
//
}
int sum() {
//
}
All sum() really does however, is add 100 to a variable. This can be incorporated into the add() function very easily via the += operator, meaning your code is equivalent to this:
int a() {
int number = 0; //Added a necessary ';'
for(int i = 0; i < 20; i++) {
if(i % 2 == 1) { //Corrected this from if(i % 2 = 1)
number += 100; //No need for the sum() function
}
}
return number;
}
The crucial aspect:
There are a lot of additional optimizations you could perform on your setup; Essentially, int a() could be simplified to
int a() {
return 1000;
}
So, you could just as easily not have a() be a function at all:
#define a() 1000
Or, (probably better):
const int a = 1000;
EDIT :
For your updated code you need to write int zmeratSonar28(); before int zmeratSonar1() starts:
int zmeratSonar28();
int zmeratSonar1() {
//Sonar code stuff
}
int zmeratSonar28() {
//Other sonar code stuff
}

Related

C++: is this a correct way to use integer variables as pointers to a function call?

I am a C++ newbie.
Context: I found this third-party snippet of code that seems to work, but based on my (very limited) knowledge of C++ I suspect it will cause problems. The snippet is as follows:
int aVariable;
int anInt = 1;
int anotherInt = 2;
int lastInt = 3;
aVariable = CHAIN(anInt, anotherInt, lastInt);
Where CHAIN is defined as follows (this is part of a library):
int CHAIN(){ Map(&CHAIN, MakeProcInstance(&_CHAIN), MAP_IPTR_VPN); }
int _CHAIN(int i, int np, int p){ return ASMAlloc(np, p, &chainproc); }
int keyalloc[16384], kpos, alloc_locked, tmp[4];
int ASMAlloc(int np, int p, alias proc)
{
int v, x;
// if(alloc_locked) return 0 & printf("WARNING: you can declare compound key statements (SEQ, CHAIN, EXEC, TEMPO, AXIS) only inside main() call, and not during an event.\xa");
v = elements(&keyalloc) - kpos - 4;
if(v < np | !np) return 0; // not enough allocation space or no parameters
Map(&v, p); Dim(&v, np); // v = params array
keyalloc[kpos] = np + 4; // size
keyalloc[kpos+1] = &proc; // function
keyalloc[kpos+2] = kpos + 2 + np; // parameters index
while(x < np)
{
keyalloc[kpos+3+x] = v[x];
x = x+1;
}
keyalloc[kpos+3+np] = kpos + 3 | JUMP;
x = ASMFind(kpos);
if(x == kpos) kpos = kpos + np + 4;
return x + 1 | PROC; // skip block size
}
int ASMFind(int x)
{
int i, j, k; while(i < x)
{
k = i + keyalloc[i]; // next
if(keyalloc[i] == keyalloc[x]) // size
if(keyalloc[i+1] == keyalloc[x+1]) // proc
{
j = x-i;
i = i+3;
while(keyalloc[i] == keyalloc[j+i]) i = i+1; // param
if((keyalloc[i] & 0xffff0000) == JUMP) return x-j;
}
i = k;
}
return x;
}
EDIT:
The weird thing is that running
CHAIN(aVariable);
effectively executes
CHAIN(anInt, anotherInt, lastInt);
Somehow. This is what led me to believe that aVariable is, in fact, a pointer.
QUESTION:
Is it correct to store a parametrized function call into an integer variable like so? Does "aVariable" work just as a pointer, or is this likely to corrupt random memory areas?
You're calling a function (through an obfuscated interface), and storing the result in an integer. It might or might not cause problems, depending on how you use the value / what you expect it to mean.
Your example contains too many undefined symbols for the reader to provide any better answer.
Also, I think this is C, not C++ code.

Multiplying a digit of a number with its current position and then add it with the others using recursion

the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}

How to calculate factorial in c++ [duplicate]

This question already has answers here:
How do I find a factorial? [closed]
(19 answers)
Closed 8 years ago.
Calculate factorials in C++ by function
I wrote this code :
int fact (int A)
{
int B ;
B= A*(A-1);
return B;
}
int main ()
{
int x;
cout <<"Enter number to calulate its factorial :"<<endl;
cin >> x ;
cout << fac (x);
}
Have you ever tried to google it before posting there?
int factorial(int n)
{
if (n < 0 ) {
return 0;
}
return !n ? 1 : n * factorial(n - 1);
}
Your fact function just computes factorial for one time. You should do something resursively like:
int fact (int A)
{
if (A <= 1) {
return 1;
}
return A*fact(A-1);
}
or if you want it in iterative way then you should do the following:
int fact (int A)
{
int B = 1, i = 2;
for (; i<=A; i++) {
B = B*i;
}
return B;
}
And why din't you search it instead.
anyway...
int n, count;
unsigned long long int factorial=1;
cout<<"Enter an integer: ";
cin>>n;
if ( n< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
else
{
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
factorial*=count; /* factorial=factorial*count */
}
cout<<factorial;
}
First of all this has nothing to do with C++ ( as your question says ). This is specific to alogorithms and they can be employed in any language.
You can use below example for your reference.
int fact (int A)
{
if (A == 0) {
return 1;
}
return A*fact(A-1);
}
int factorial (int a) {
return a==0 ? 1 : a*factorial(a-1);
}
Since you're using C++ rather than C, I'd simply go with a template function. Bonus for this: due to expansion/implementation at compile time, your code will be highly optimized and essentially as fixed as possible with little to no overhead:
// First the generic template for pretty much all numbers
template <unsigned int X>
unsigned int factorial() {
return X * factorial<X - 1>();
}
// Now the specialization for the special case of 0
template <>
unsigned int factorial<0>() {
return 1;
}
For example, to calculate the factorial of 5, you'd just call factorial<5>(). With optimizations enabled, this will result in just 120. Unfortunately this is not possible with dynamic variables.

Thread 1: EXC_Bad_Access (Code=1, address=0x7fff55056148) While Trying to Use Ofstream and an integer data type named count

I am currently working to solve Project Euler's Problem #60: http://projecteuler.net/problem=60 (Just in case if you want to try and follow my logic).
The issue is that after I build my code (Which it completes without errors) and then run it, I get the error code "Thread 1: EXC_Bad_Access (Code=1, address=0x7fff55056148)" from the IDE I was using while running it (The IDE's built in debugger I think). More Specifically the error occurs only within my "Combinations" Function. The lines that get highlighted are disabled with "//" comment lines within my combinations function. Thus, currently, my code will run without any errors because all the error-causing lines are disabled as comments. if you de-comment any of those lines or any combination of those lines thereof, the code runs into the same error code listed above.
Personal Comments from Experimentation:
What I found was that any line that has something to do with either ofstream or the integer that I initialized called count causes the error. ofstream kind of makes sense, but even after disabling all lines of code related to ofstream, suddenly the integer count starts creating the error.
Any help would be much appreciated! I am still a beginner with C++, (started about two to three weeks ago.)
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
/* double x = 2 , y = 2 , b = 3, s = 2; */
/* int z, c = 1, v = 3000; */
int AllPrimes[3000];
/* int AllCombos[2018257871250650][5]; */ // disabled this line for now.
//Used to be within Combinations; Moved here to circumvent "Bad Access" Error
int FindPrimes();
int TestforPrime(double y);
int Combinations();
int WriteArrayToFile(int *ArrayPointer,int ArrayLength, string FileName, char Append);
int main()
{
cout<<FindPrimes();
cout<<Combinations();
}
int Combinations() {
int i1, i2, i3, i4, i5, /* ai */ bi, ci, di, ei;
int ZeroPointBreaker=0;
//ofstream BufferFlushed ("/Users/Yash/Xcode/Projects/Project Euler Programs/Project Euler Problem 60 (Weird Prime Cocatenate Property Problem)/I:O Files/");
int count=0;
int Buffer[9000000][5];
for (i1=0; i1<2996; i1++) {
count++;
// cout<<"Index 1 Iteration: "<<i1<<" || Count Value: "<<count<<"\n";
bi = i1 + 1;
for (i2=bi; i2<2997; i2++) {
count++;
// cout<<"Index 2 Iteration: "<<i2<<" || Count Value: "<<count<<"\n";
ci = i2+ 1;
for (i3=ci; i3<2998; i3++) {
count++;
di = i3 + 1;
for (i4=di; i4<2999; i4++) {
count++;
ei = i4 + 1;
for (i5=ei; i5<3000; i5++) {
count++;
// Buffer[count][0]=AllPrimes[i1];
// Buffer[count][1]=AllPrimes[i2];
// Buffer[count][2]=AllPrimes[i3];
// Buffer[count][3]=AllPrimes[i4];
// Buffer[count][4]=AllPrimes[i5];
}
}
}
//Flush Here
// count=0;
/* for (int i=0; i<9000000; i++) {
if (Buffer[i][1]==0) {ZeroPointBreaker=i; break;}
} */
// for (int i=0; i<ZeroPointBreaker; i++) {
// BufferFlushed<<Buffer[i][1]<<','<<Buffer[i][2]<<','<<Buffer[i][3]<<','<<Buffer[i][4]<<','<<Buffer[i][5]<<'\n';
// }
}
}
//End of Code Statements
//BufferFlushed.close();
return 0;
}
int FindPrimes() {
cout.precision(0);
AllPrimes[0]=2;
double b = 3, s = 2;
int z, c = 1, v = 3000;
while ( c != v ) {
z = TestforPrime(b);
if ( z == 1 ) {
AllPrimes[c]=b;
c = c + 1;
s = s + b;
if ( c == v ) {
cout<<fixed<<" Prime="<<b<<" Count="<<c<<" "<<"Sum="<<s<<"\n";
int success = WriteArrayToFile(AllPrimes,3000,"/Users/Yash/Xcode/Projects/Project Euler Programs/Project Euler Problem 60 (Weird Prime Cocatenate Property Problem)/I:O Files/AllPrimes.txt",'n');
cout<<"\n Write Success (0=Successful): "<<success<<"\n";
if (success == 0) {return 0;}
else {return 1;}
}
else {
};
}
else {
};
b = b + 2;
}
}
int WriteArrayToFile(int *ArrayPointer,int ArrayLength, string FileName, char Append) {
if (Append == 'y') {
ofstream OutputFile (FileName, ios::app);
for ( unsigned long long i1=0 ; i1 < ArrayLength ; i1++) {
OutputFile<<ArrayPointer[i1]<<"\n";
}
OutputFile.close();
return 0;}
else if (Append == 'n') {
ofstream OutputFile (FileName);
for ( unsigned long long i1=0 ; i1 < ArrayLength ; i1++) {
OutputFile<<ArrayPointer[i1]<<"\n";
}
OutputFile.close();
return 0;}
}
int TestforPrime (double y) {
double x = 2;
while ( x <= y ) {
if ( (( y / x ) - int( y / x )) == 0 ) {
if ( y == x ) {
return 1;
}
else {
return 0;
}
}
x = x + 1;
}
}
This variable:
int Buffer[9000000][5];
takes up 45000000 * 4 Bytes. That's 180MB. You can't fit that on the stack. Use a global variable or dynamic allocation (or, more likely, another solution - I haven't looked at the problem itself, so don't know if your solution is "right").

Effect on performance when using objects in c++

I have a dynamic programming algorithm for Knapsack in C++. When it was implemented as a function and accessing variables passed into it, it was taking 22 seconds to run on a particular instance. When I made it the member function of my class KnapsackInstance and had it use variables that were data members of that class, it started taking 37 seconds to run. As far as I know, only accessing member functions goes through the vtable so I'm at a loss to explain what might be happening.
Here's the code of the function
int KnapsackInstance::dpSolve() {
int i; // Current item number
int d; // Current weight
int * tbl; // Array of size weightLeft
int toret;
tbl = new int[weightLeft+1];
if (!tbl) return -1;
memset(tbl, 0, (weightLeft+1)*sizeof(int));
for (i = 1; i <= numItems; ++i) {
for (d = weightLeft; d >= 0; --d) {
if (profitsWeights.at(i-1).second <= d) {
/* Either add this item or don't */
int v1 = profitsWeights.at(i-1).first + tbl[d-profitsWeights.at(i-1).second];
int v2 = tbl[d];
tbl[d] = (v1 < v2 ? v2 : v1);
}
}
}
toret = tbl[weightLeft];
delete[] tbl;
return toret;
}
tbl is one column of the DP table. We start from the first column and go on until the last column. The profitsWeights variable is a vector of pairs, the first element of which is the profit and the second the weight. toret is the value to return.
Here is the code of the original function :-
int dpSolve(vector<pair<int, int> > profitsWeights, int weightLeft, int numItems) {
int i; // Current item number
int d; // Current weight
int * tbl; // Array of size weightLeft
int toret;
tbl = new int[weightLeft+1];
if (!tbl) return -1;
memset(tbl, 0, (weightLeft+1)*sizeof(int));
for (i = 1; i <= numItems; ++i) {
for (d = weightLeft; d >= 0; --d) {
if (profitsWeights.at(i-1).second <= d) {
/* Either add this item or don't */
int v1 = profitsWeights.at(i-1).first + tbl[d-profitsWeights.at(i-1).second];
int v2 = tbl[d];
tbl[d] = (v1 < v2 ? v2 : v1);
}
}
}
toret = tbl[weightLeft];
delete[] tbl;
return toret;
}
This was run on Debian Lenny with g++-4.3.2 and -O3 -DNDEBUG turned on
Thanks
In a typical implementation, a member function receives a pointer to the instance data as a hidden parameter (this). As such, access to member data is normally via a pointer, which may account for the slow-down you're seeing.
On the other hand, it's hard to do more than guess with only one version of the code to look at.
After looking at both pieces of code, I think I'd write the member function more like this:
int KnapsackInstance::dpSolve() {
std::vector<int> tbl(weightLeft+1, 0);
std::vector<pair<int, int> > weights(profitWeights);
int v1;
for (int i = 0; i <numItems; ++i)
for (int d = weightLeft; d >= 0; --d)
if ((weights[i+1].second <= d) &&
((v1 = weights[i].first + tbl[d-weights[i-1].second])>tbl[d]))
tbl[d] = v1;
return tbl[weightLeft];
}