I came across a program with 10 header and 10 source files. I read in my text book that the functions are called from main. But how can I pass data to so many functions from main()?
Functions don't necessarily need to called from main. They can be called by other functions. For example:
int foo(int x)
{
return x*x;
}
int bar(int x)
{
return foo(x) + 1;
}
int main()
{
int a = bar(42);
std::cout << a << std::endl;
return 0;
}
Note that foo() is never called directly from main().
To my mind, this phrase isn't correct, but I guess what was meant to be said could be rephrased like "Every function or class method that you implement and use would be somehow called from your main() routine"
And somehow in this context would actually mean directly or indirectly - via other functions / function wrappers.
Anyway, the idea should be clear - any significant action that is done in your application is actually done using some function call from your main() routine, which is sometimes also called application root (try to think of your application as a tree of function calls and then your main() function would be right in the top of your tree).
Related
Hello i am totally new to c++ programming, I had a question when we use a int function why do we have to use return command like we can use cout << sum << endl; and call the function in main(). but for return we have to do like cout << printSum();
Case 1:
#include <iostream>
using namespace std;
int addNumbers(int x, int y){
int sum = x + y;
cout << sum << endl;
}
int main() {
addNumbers(4, 5);
return 0;
}// without using return
Case 2:
#include <iostream>
using namespace std;
int addNumbers(int x, int y){
int sum = x + y;
return sum;
}
int main() {
cout << addNumbers(4, 5) << endl;
return 0;
}// return method
return statement is seemingly very basic, but in fact, one of the most puzzling aspects of procedural programming for freshman students in our local university.
What are the functions anyway?
Functions are the building blocks of procedural and functional programming languages. You might think of a function as of reusable, maintainable block of code responsible for some action. If you perform some operations often together, you might want to "pack" them inside a function. A "good" function is a little machine that takes some input data and gives back processed data.
In C++ you can "share" the results of the processing with "outside code" by returning a value, modifying a parameter (worse) or modifying the global state (worst).
In simple case, "returning" functions are direct analogs of math functions like y = f(x) (even the call syntax is very similar). As a programmer you just define what is x, what is y and how exactly f maps x to y.
Printing vs returning
Now, the printing into console (terminal) and returning are not the same. In simple words, printing is just showing the user some characters on the screen ("speaking with user"). Returning from function allows to receive the result from function ("speaking with outside code"), but it's invisible for the user unless you print it afterwards .
Different function layouts you may encounter while learning
(does not pretend to be an exhaustive list)
So, in your class or tutorial sometimes they teach you how to
(1) print an object directly within main()
int main() {
int i = 42 + 13;
std::cout << i << std::endl;
}
(2) print an object inside a function
void printSum(int a, int b) {
int i = a + b;
std::cout << i << std::endl;
}
int main() {
printSum(42, 13);
}
(3) return an object from the function and printing afterward
void sum(int a, int b) {
return a + b;
}
int main() {
int s = sum(42, 13);
std::cout << s << std::endl;
}
Obviously, (1) is not reusable at all: to change parameters you must intervene into the program logic. Also, if logic is something more than just a sum, main() function will grow quickly in size and become unmaintainable. Responsibilities will be scattered across the code, violating Single responsibility principle
(2) is better in all aspects: function encapsulates logic in a separate place in code, has distinctive name, can be changed separately from main function. Function can be called with different values, and changing arguments doesn't change the function.
But it still has 2 responsibilities: perform the calculation and output to the screen. What if you want not to print the result, but write it to a file? or send it via network? or just discard it? You will need to write another function. The logic inside this new function will be the same, thus introducing duplication and violating DRY principle. Also, (2) is not a pure function because it is modifying std::cout which is basically the global state (we say that this function has "side effects").
Also, you can think about (2) as if it was (1), but with whole program logic moved from main() into a separate function (that's why sometimes functions are called "subprograms").
(3) solves the multiple responsibility problem, by getting rid of printing (moving it into the "user code"). The function contains only pure logic. Now it's a number crunching machine. In main function you can decide what to do with the result of the calculations without touching the calculating function. It becomes a "black box". No need to worry how it is implemented, and no need to change anything, it just works.
In your post there is a shorter version of (3):
int main() {
std::cout << sum(42, 13) << std::endl;
}
The difference is that no temporary object int s being created, but return value is being written directly to std::cout (in fact, passed as a parameter to a function called operator<<)
In real life
In real-life programming, most of the time you will be writing functions like (3), that don't print anything. Printing to terminal is just a quick and simple way to visualize data. That's why you've been taught how to output to standard streams rather than writing to the files, network sockets or showing GUI widgets. Console printing is also very handy during debugging.
See also:
Call Stack - Wikipedia to better understand how function calls happen under the hood
The Definitive C++ Book Guide and List might be of help too.
P.S. There is a big deal of simplification in this post, thus the usage of lots of quoted terms.
The int function must return an int. If you don't want to return values, you can use a void function:
#include <iostream>
using namespace std;
void addNumbers(int x, int y){
int sum = x + y;
cout << sum << endl;
}
int main() {
addNumbers(4, 5);
return 0;
}
The main() must return int (standard), which means that the program ran successfully (0). You can even leave the return statement out of main(), but it will return zero (implicit).
#include <iostream>
using namespace std;
void addNumbers(int x, int y){
int sum = x + y;
cout << sum << endl;
}
int main() {
addNumbers(4, 5);
}
You have two slightly different scenario in both of your snippets.
Case 1: You are printing the value from the called function, before the function finishes execution. So, you don't (need to) return any value. So you don't need a return statement.
Case 2: You are expecting the function to return the value which will get printd. So, you need to have a the return in your called function.
This is because of the return types of the function. Some times you want a function to give you a result instead of just doing things with the information you put into it.
Just like a variable has a type such as int and string, a function wants a type for the item it will be returning.
Here is a website which might help you get into the basics of functions including information about return types.
Suppose I am using a library which implements the function foo, and my code could look something like this:
void foo(const int &) { }
int main() {
int x = 1;
foo(x);
std::cout << (1/x) << std::endl;
}
Everything works fine. But now suppose at one point either foo gets modified or overloaded for some reason. Now what we get could be something like this:
void foo(int & x) {
x--;
}
void foo(const int &) {}
int main() {
int x = 1;
foo(x);
std::cout << (1/x) << std::endl;
}
BAM. Suddenly the program breaks. This is because what we actually wanted to pass in that snippet was a constant reference, but with the API change suddenly the compiler selects the version we don't want and the program breaks unexpectedly.
What we wanted was actually this:
int main() {
int x = 1;
foo(static_cast<const int &>(x));
std::cout << (1/x) << std::endl;
}
With this fix, the program starts working again. However, I must say I've not seen many of these casts around in code, as everybody seems to simply trust this type of errors not to happen. In addition, this seems needlessly verbose, and if there's more than one parameter and names start to become longer, function calls get really messy.
Is this a reasonable concern and how should I go about it?
If you change a function that takes a const reference so that it no longer is a const, you are likely to break things. This means you have to inspect EVERY place where that function is called, and ensure that it is safe. Further having two functions with the same name, one with const and one without const in this sort of scenario is definitely a bad plan.
The correct thing to do is to create a new function, which does the x-- variant, with a different name from the existing one.
Any API supplier that does something like this should be severely and physically punished, possibly with slightly less violence involved if there is a BIG notice in the documentation saying "We have changed function foo, it now decrements x unless the parameter is cast to const". It's one of the worst possible binary breaks one can imagine (in terms of "it'll be terribly hard to find out what went wrong").
If I just do it:
Ex1:
#include <iostream>
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
I get compilation error! Because the compile doesn´t know what is "doSomething".
But if I change the position of doSomething to come in first place, the program compiles successfully.
Ex2:
#include <iostream>
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
int main()
{
//try to call doSomething function
doSomething();
}
I can declare prototype to be like this:
Ex3:
#include <iostream>
void doSomething(void);
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
But why the first example does not work? Why I even have to declare a prototype or call functions first and main function at last?
Thanks!
You can't call a function without the compiler having seen either the definition or a declaration, first -- simple as that. A prototype or the actual definition must appear before a call.
Because the compiler hasn't seen doSomething before it's used.
Either you must prototype it, or define it first, so that the compiler knows how to analyze the usage of it.
This is a legacy from C. C is a single pass language which means that it has to do everything by only reading the file once. To be able to call a function without a forward declaration/prototype would require reading the file twice; The first time to find all the function signatures and the second time to actually compile.
C++ kept this requirement for features that were part of C, such as free functions and global variables. However classes are new to C++ and there was no need to keep the old way of doing things. So within a single class definition, multi-pass compilation is used. That's why you can do this:
class MyClass {
void foo() {bar();}
void bar() {}
};
But you can't do what you listed in your question.
If I have a function A(), I am interested in finding a convenient method to create a function B() that has the exact same functionality as A(), differing only in name. The new function would be for a one-time use. The intent is to differentiate between calls to the same function in a somewhat primitive sampling profiler, and the duplicated function would only be used in this context. That is, it would never touch production code and only be used for tinkering.
First guess would be a macro that declares a function named B and creates an inlined call to A() inside of it. The problem here is that I'm not aware of a method in GCC to force an arbitrary function call to inline; it seems all inlining options are for function declarations rather than calls.
There may be some esoteric way to do it with templates, or possibly by tricking the compiler into inlining. I'm not sure it's possible. Any thoughts? Unfortunately the new C++ standard is not available, if it would make a difference.
Using templates
template<int x>
void A()
{
// ..
}
int main()
{
A<0>();
A<1>();
return 0;
}
Update
The compiler can be too smart and create only one body for A<0> and A<1>. At least Visual C++ 2010 does it in Release mode. To prevent it, just use the template parameter inside the function template body in logs or asserts. For example,
#include <iostream>
template<int x>
void A()
{
::std::cout << x << std::endl;
// ..
}
int main()
{
A<0>();
A<1>();
auto v0 = A<0>;
auto v1 = A<1>;
::std::cout << v0 << std::endl;
::std::cout << v1 << std::endl;
::std::cout << (v0 == v1) << std::endl;
return 0;
}
This works using templates:
#include <iostream>
template<typename T>
void foo() {
static int x = 0;
std::cout << &x << std::endl;
}
int main(int argc, char **argv) {
foo<int>();
foo<float>();
return 0;
}
If you execute that, you'll see two different values printed, reflecting the compiler generated code for both calls, even though the template parameter is unused. nm on the object file confirms this.
If this is a one-time debug hack, then why not:
#define A_CONTENT \
... // whatever
void A()
{
A_CONTENT
}
void B()
{
A_CONTENT
}
...
A(); // Call to A
B(); // Call to B
Macros are generally grim, but we're not talking about production code here, so who cares?
Having been down this road myself, the short answer is that even if you get the compiler to emit two identical duplicates of a function, the optimizing linker will notice that they're identical and fold them back together into one implementation. (And if you've turned off optimization in the linker, then your profile isn't valid anwyay).
In the context of a sampling profiler, I've found the easier approach is to make two tiny wrappers for the function instead:
void Func() { .... }
_declspec(noinline)
void A_Func( return Func(); }
void B_Func( return Func(); }
void C_Func( return Func(); }
Then when your profiler samples the callstack, you'll be able to differentiate between the different callsites of this function in a very straightforward way..
You could always define a macro, for example in Chromium we do the following to reuse code:
#define CHROMEG_CALLBACK_1(CLASS, RETURN, METHOD, SENDER, ARG1) \
static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, \
gpointer userdata) { \
return reinterpret_cast<CLASS*>(userdata)->METHOD(sender, one); \
} \
\
virtual RETURN METHOD(SENDER, ARG1);
And we call them like:
CHROMEGTK_CALLBACK_1(PageActionViewGtk, gboolean, OnExposeEvent, GdkEventExpose*);
CHROMEGTK_CALLBACK_1(PageActionViewGtk, gboolean, OnButtonPressed, GdkEventButton*);
You can do something similar to do what you wanted. The above example shows us using two different implementations but with one common code base. For GTK callbacks.
It's a little unclear what you're really trying to do, but a really ugly solution would be to declare the body of A as a macro and then you can "inline" this macro within whatever functions you like.
Also, macros are evil. Never use them unless you really have to.
Why do you care so much about inlining it? If you create a wrapper function, there is a pretty good chance the compiler will inline it anyway. At the very least, you're unlikely to get a function frame constructed.
C++11 also lets you do this:
void A() {
...
}
...
auto B = [] () -> void { A(); };
You can now use B syntactically as though it was a function wrapping A.
I declared a global function in a .cpp file void functionA(). I would like functionA() to be called exactly once before the start-up ( not inside main()). The thing I realize is if the function is int functionB(), I could call it using static int A = functionB(). But for return value of void, how could I do that?
Thanks
You put it into the constructor of a global object:
void functionA();
namespace {
struct global_initializer {
global_initializer() {functionA();}
} the_global_initializer;
}
Note that this has the common drawbacks of global initialization: While globals within the same translation unit are initialized in the order of their definition, the order of initialization of globals across translation units is undefined.
Also, linkers might choose to eliminate unreferenced objects (the_global_initializer), which would prevent functionA() from being called.
static int a = functionA(), 42;
There are few places where comma expressions are useful, but this may be one of them.
You could use a static struct, it's constructor will get called before main.
#include <iostream>
void functionA(void)
{
std::cout << "Hello, ";
}
static struct BeforeMain
{
BeforeMain(void)
{
// stuff in this constructor is executed before "main" function
functionA();
}
} g_beforeMain; // shouldn't get used though
int main(void)
{
std::cout << "world!" << std::endl;
return 0;
}
This will print Hello, world!, although I'm new to C++, so this may not be the best approach.
Solution 1: Make that void function to have a return type (say int) and return a dummy return value
If you can't do Solution 1,
Solution 2: Write a wrapper function as shown. Make sure to write code so that wrapper can be called only once (unless it is fine to do so multiple times)
Wrap it up! (and document extensively).
void fA(){}
int wrapper(){
// Have checks here to ensure it is not called more than once
fA();
return 0;
}
// Extensively document such as `'x' is a bogus dummy variable.`
static int x = wrapper();
int main(){
}