Calling a function in C++ - c++

I'm new to the whole C++ programming thing, and I know this is a easy solution, but I just cant figure it out!
I simply just wanna call a function that prints out 1 + 4.
Here's the code:
#include <iostream>
using namespace std;
int func()
{
cout << 1 + 4;
return 0;
}
int main()
{
int func();
}
It shows nothing in the console window, only that the application stopped with return code 0.
Can someone tell me what's wrong?

You are not calling func() function correctly:
int main()
{
// int func(); This line tries to declare a function which return int type.
// it doesn't call func()
func(); // this line calls func() function, it will ouput 5
return 0;
}

you can just call the function by its name. Like func();
int func()
{
cout << 1 + 4;
return 0;
}
the above function is retruning an integer. you are returning 0. to make it more useful return the sum and catch it in main function.
int func(){
return 1+4;// return 5 to main function.
}
now in main.
int main (){
int ans = func();// ans will catch the result which is return by the func();
cout<<ans;
return 0;
}
try to understand the working of each statement.

Related

friend function not printing out what it should

whenever I run the program, there is no output, the program just ends. Am i doing something wrong? I'm sure there's something i missed but i can't seem to figure it out.
#include <iostream>
#include <string>
using namespace std;
class Addr
{
public:
Addr(int i = 0){
total = i;
}
void addNum(int num){
total += num;
}
int getNum(){
return total; }
friend int print(Addr& var);
private:
int total;
};
int print(Addr& var){
return var.total;
}
int main()
{
Addr object1;
object1.addNum(3);
print(object1);
return 0;
}
Your program behaves correctly. There is no output because you are not printing anything to the console in your program.
The print function merely returns the total.
If you wish to print the value to the console then you could for example change the definition as follows:
int print(Addr& var){
cout << var.total << endl; // this prints to the console output
return var.total;
}
There is no issue with your code. The fact is that no print function is used. I have modified your main function.
int main()
{
Addr object1;
object1.addNum(3);
cout<<print(object1);
return 0;
}

How do I return value to main function without directly calling the function

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.
Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.
In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

replace all negative value from array using recursion C

I want replace all negative value by zero(recursively). And I have use C and recursion. It's was my homework.
Desired output:
0 4 0 3
What I get:
0 4 -9 3
My code:
#include <stdio.h>
int zeros_value(int n, int tab[])
{
if (n==0) return 0;
if(tab[n-1] < 0){
tab[n-1]=0;
}
else{
return zero_value(n-1,tab);
}
}
int main(void)
{
int tab[4] = {0,4,-9,3};
int number = 0;
int i;
zero_value(4, tab);
for(i=0;i<4;i++)
printf("%d ", tab[i]);
return 0;
}
When you hit the first negative, the recursion doesn't continue anymore and the function returns. You don't really need to return any value from the function. You can rewrite it to make a void function.
#include <stdio.h>
void zero_value(int n, int tab[])
{
if (n==0) return;
if(tab[n-1] < 0) tab[n-1]=0;
zero_value(n-1,tab);
}
int main(void)
{
int tab[4] = {0,4,-9,3};
int number = 0;
int i;
zero_value(4, tab);
for(i=0;i<4;i++)
printf("%d ", tab[i]);
return 0;
}
I see the following problems with your code.
The function zero_values does not have a valid return statement when tab[n-1] is negative. You can see it more clearly if you change the function to:
int zeros_value(int n, int tab[])
{
if (n==0)
{
return 0;
}
if(tab[n-1] < 0)
{
tab[n-1]=0;
// No return here.
}
else
{
return zero_value(n-1,tab);
}
// No return here either.
}
Calling such functions leads undefined behavior.
The printf line in main is not right.
printf("%d%d%d%d", zeros_value(4,tab));
That line needs four arguments of type int after the format string to work correctly. Not providing enough arguments to printf is also cause for undefined behavior.
You can use solution provided in the answer by #usr to solve both problems.
If you have any valid reasons to return an int from zero_value, you need to change the implementation appropriately. It's not clear from your post what that return value is supposed to be.

C++ reinterpret cast is inconsistent

I made a test program:
#include <iostream>
using namespace std;
class Bug {
private:
char a[25];
int& view (int i) {
return *reinterpret_cast<int*>(&a[i]);}
public:
Bug () {}
void overwrite () {
view(a[0]) = 2;
cout << "value of a[0] is: " << view(a[0]) << endl;
}
};
int main () {
Bug b;
b.overwrite();
return 0;
}
... where I'm testing the view function. Everything works as I'd expect; the value beginning at a[0] is 2, as the print statement in the void method shows.
However, I modify the program slightly:
#include <iostream>
using namespace std;
class Bug {
private:
int x;
char a[25];
int& view (int i) {
return *reinterpret_cast<int*>(&a[i]);}
public:
Bug () {}
void overwrite () {
view(a[0]) = 2;
cout << "value of a[0] is: " << view(a[0]) << endl;
}
};
int main () {
Bug b;
b.overwrite();
return 0;
}
Notice that I added a private member variable int x. This was the only change. The moment I do this, the print statement in the overwrite method no longer prints 2, as in the previous program -- it returns a garbage value (and sometimes the correct value, 2).
More importantly, sometimes the correct value will show, but the program will segfault.
Anybody know what's happening under the hood?
Bonus question. for values lower than 25, my private variable char a[value] will show compiler warnings that mention stack smashing (using g++-4.7).

My C++ Program isn't executing my cout code

I am learning C++, and I am trying to make a simple program which prints 5 variables, as my book said to do this, but it is not executing my code.
#include<iostream>
using namespace std;
int main()
{
//Program Code below
return 0;
char letter; letter = 'A'; //Declared, then initialized
int number; number = 100; //Declared, then initialized
float decimal = 7.5; //Declared AND initialized
double pi = 3.14159; //Declared AND initialized
bool isTrue = false; //Declared AND initialized
cout<<"Char letter: "<<letter<<endl;
cout<<"Int number: "<<number<<endl;
cout<<"Float decimal: "<<decimal<<endl;
cout<<"Double pi: "<<pi<<endl;
cout<<"Bool isTrue: "<<isTrue<<endl;
}
As soon as your code executes this line
return 0;
no other lines of your code will be executed - from a practical point of view, your program will have ended. Move this line down so that it is the last line of code executed by your main() function.
Your problem is that you are returning from main before doing anything:
int main()
{
return 0; // HERE!!
// no code after return gets executed
}
Your return 0; should be at the end of main, not the start
Please re-position the "return 0;" statement
Since main is a function that returns an integer, the execution of the main function is primarily to return some integral value. As soon as the value is returned, the function assumes its job is complete and hence does no longer hold the control of the program.
Your code:
#include<iostream>
using namespace std;
int main()
{
return 0; // Function thinks its job is done hence it ignores everything after it.
...some other code
}
Actually what you wish to do:
#include<iostream>
using namespace std;
int main()
{
... useful code
return 0; // Okay. Returning is alright, as the useful job is done.
}