I need help making an c++ program with a function that uses int Disc(int A, int B, int C) and calculates returns B*B-4*A*C and use the function Disc in the program..... i have this so far.
void main(){
cout << Disc(a,b,c);
}
What does the book you are using say about functions?
Assuming you can't get a book, take a look that this tutorial on functions (See the edit below)
You already have the function definition. The name, what parameters it takes and what it returns so if you take some time looking at the above tutorial you should be able to put something together (All you need to do is to write the body of the function).
The one thing that may cause you an issue (compiler error) is if you don't put it above the main function as either the function definition or the function itself must come before it is used. For simplicity at this point I reccomend you just put the function itself above the main function as shown in first example in the tutorial I linked to.
EDIT about linked tutorial
It suggests you use return with brackets. Example:
return (5);
Where as it should be used without them. Example:
return 5;
Ok, so you define the function Disc then:
int Disc(int A, int B, int C)
{
/* tricky part goes here... */
}
Related
I am writing some C++ code to get data from a SDR (software defined radio) and analyse it using an FFT library (FFTW3). The software uses an API (SDR_play_API and its DLL). I am trying to include the API functionality into an object. The library comes with a non-object based example program.
The IDE I am using is VS2105.
Three of the functions are callbacks to handle events from the hardware. The address of the callback functions that handle these events are passed to the API through a structure. I include the relevant code snippets from the example program, the header files and my own code after a description of the problem.
Though I have been on some C++ training - and taught others the basics - I am far from an expert and the problem goes beyond my understanding of pointers and objects.
The problem I have is one that has been discussed before on Stack Exchange. It is a problem of pointers to member functions.
The simple solution would seem to be to make the functions STATICs. However that causes problems because of some of the variables used in these functions. Without making them static then the compiler complains and if I make them static the linker complains because there is no matching definition for static variables in the library.
I have looked through Stack Exchange tried the solutions suggested but I can't seem to make any of them work - I get compiler errors.
So I feel ideally I just want to pass the pointers to the member functions to API through the structure ... but I have tried all sorts of variations on syntax without success. Can anyone help?
The API comes with an example program that does not use objects. So before I reveal my attempts to use the functions in an object, here is the code from the example program. First I will show where it assigns the location of the functions to the members of the structure, then I will include the structure definitions etc from the header file.
First then, the assignment:
// Assign callback functions to be passed to sdrplay_api_Init()
cbFns.StreamACbFn = StreamACallback;
cbFns.StreamBCbFn = StreamBCallback;
cbFns.EventCbFn = EventCallback;
Here, from the header file that comes with the API, is the definition of the structure
{
sdrplay_api_StreamCallback_t StreamACbFn;
sdrplay_api_StreamCallback_t StreamBCbFn;
sdrplay_api_EventCallback_t EventCbFn;
} sdrplay_api_CallbackFnsT;
and here, again from the header file that comes with the API is the definition of the data types - you can see the these are function pointers
typedef void (*sdrplay_api_StreamCallback_t)(short *xi, short *xq, sdrplay_api_StreamCbParamsT *params, unsigned int numSamples, unsigned int reset, void *cbContext);
typedef void (*sdrplay_api_EventCallback_t)(sdrplay_api_EventT eventId, sdrplay_api_TunerSelectT tuner, sdrplay_api_EventParamsT *params, void *cbContext);
here is one of the call back function declarations
void StreamACallback(short *xi, short *xq, sdrplay_api_StreamCbParamsT *params, unsigned int numSamples, unsigned int reset, void *cbContext)
{
...
}
So that all works fine and compiles - but it that works in a non-object scenario.
However when I make the functions a member of a class then I get errors. I have tried the following variations without success. Can someone please point me in the right direction - if I had had hair by now I wouldn't have anymore cause it would be on the floor all around me in clumps.
function definition:
void sdr_object::StreamACallback(short *xi, short *xq, sdrplay_api_StreamCbParamsT *params, unsigned int numSamples, unsigned int reset, void *cbContext)
{
...
}
Unsuccessful attempts to assign to structure include (including compiler error)
cbFns.StreamACbFn = this->StreamACallback;//"non standard syntax: use '&' to create a pointer to the member"
//cannot convert from 'void (__cdecl sre_object::*)(...) to sdrplay_api_StreanCallback_t
cbFns.StreamACbFn = &this->StreamACallback;//'&': illegal operation on bound member function experssion
cbFns.StreamACbFn = this->sdr_object::StreamACallback; //"non standard syntax: use '&' to create a pointer to the member"
//cannot convert from 'void (__cdecl sre_object::*)(...) to sdrplay_api_StreanCallback_t
cbFns.StreamACbFn = &this->sdr_object::StreamACallback; //'&': illegal operation on bound member function experssion
Any wisdom will e received most gratefully. (How to do it will be received even more gratefully ...!)
This answer comes with many thanks to Igor Tandetnik who suggested the solution in comments above.
Igor wrote "Make your callbacks static member functions. Pass this pointer for cbContext parameter to sdrplay_api_Init - you get that same pointer back in the callback. Now the callback can do static_cast<MyClass*>(cbContext)->memberFunction(params); . The actual logic can now be implemented in a non-static member function; the static one just serves as a glue between C++ implementation and C API"
My implementation of that is as follows:
Add to the class declaration in the header file an intermediary "glue" function for each event handler e.g.:
static void sdr_object::StreamACallback_static(short *xi, short *xq, sdrplay_api_StreamCbParamsT *params, unsigned int numSamples, unsigned int reset, void *cbContext)
{
static_cast<sdr_object*>(cbContext)->StreamACallback(xi, xq, params, numSamples, reset, cbContext);
};
For the function above, the pointer that is handed to the API then becomes
cbFns.StreamACbFn = this->StreamACallback_static;
In my particular example, I then had to do the same for the other two functions.
I did not have to change any other existing code.
Again, many thanks to Igor for the answer - I hope I have implemented it as he intended ... that said, what I have described works, so I imagine I have!
I was taught that functions need declarations to be called. To illustrate, the following example would give me an error as there is no declaration for the function sum:
#include <iostream>
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
// main.cpp:4:36: error: use of undeclared identifier 'sum'
// std::cout << "The result is " << sum(1, 2);
// ^
// 1 error generated.
To fix this, I'd add the declaration:
#include <iostream>
int sum(int x, int y); // declaration
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
Why the main function doesn't need the declaration, as other functions like sum need?
A definition of a function is also a declaration of a function.
The purpose of a declaring a function is to make it known to the compiler. Declaring a function without defining it allows a function to be used in places where it is inconvenient to define it. For example:
If a function is used in a source file (A) other than the one it is defined in (B), we need to declare it in A (usually via a header that A includes, such as B.h).
If two or more functions may call each other, then we cannot define all those functions before the others—one of them has to be first. So declarations can be provided first, with definitions coming afterward.
Many people prefer to put “higher level” routines earlier in a source file and subroutines later. Since those “higher level” routines call various subroutines, the subroutines must be declared earlier.
In C++, a user program never calls main, so it never needs a declaration before the definition. (Note that you could provide one if you wished. There is nothing special about a declaration of main in this regard.) In C, a program can call main. In that case, it does require that a declaration be visible before the call.
Note that main does need to be known to the code that calls it. This is special code in what is typically called the C++ runtime startup code. The linker includes that code for you automatically when you are linking a C++ program with the appropriate linker options. Whatever language that code is written in, it has whatever declaration of main it needs in order to call it properly.
I was taught that functions need declarations to be called.
Indeed. A function must be declared before it can be called.
why we don't add a declaration for the main function?
Well, you didn't call main function. In fact, you must not call main at all1, so there is never a need to declare main before anything.
Technically though, all definitions are also declarations, so your definition of main also declares main.
Footnote 1: The C++ standard says it's undefined behaviour to call main from within the program.
This allows C++ implementations to put special run-once startup code at the top of main, if they aren't able to have it run earlier from hooks in the startup code that normally calls main. Some real implementations do in fact do this, e.g. calling a fast-math function that sets some FPU flags like denormals-are-zero.
On a hypothetical implementation, calling main could result in fun things like re-running constructors for all static variables, re-initializing the data structures used by new/delete to keep track of allocations, or other total breakage of your program. Or it might not cause any problem at all. Undefined behaviour doesn't mean it has to fail on every implementation.
The prototype is required if you want to call the function, but it's not yet available, like sum in your case.
You must not call main yourself, so there is no need to have a prototype. It's even a bad a idea to write a prototype.
No, the compiler does not need a forward declaration for main().
main() is a special function in C++.
Some important things to remember about main() are:
The linker requires that one and only one main() function exist when creating an executable program.
The compiler expects a main() function in one of the following two forms:
int main () { /* body */ }
int main (int argc, char *argv[]) { /* body */ }
where body is zero or more statements
An additional acceptable form is implementation specific and provides a list of the environment variables at the time the function is called:
int main (int argc, char* argv[], char *envp[]) { /* body */ }
The coder must provide the 'definition' of main using one of these acceptable forms, but the coder does not need to provide a declaration. The coded definiton is accepted by the compiler as the declaration of main().
If no return statement is provided, the compiler will provide a return 0; as the last statement in the function body.
As an aside, there is sometimes confusion about whether a C++ program can make a call to main(). This is not recommended. The C++17 draft states that main() "shall not be used within a program." In other words, cannot be called from within a program. See e.g. Working Draft Standard for C++ Programming Language, dated "2017-03-21", Paragraph 6.6.1.3, page 66. I realize that some compilers support this (including mine), but the next version of the compiler could modify or remove that behavior as the standard uses the term "shall not".
It is illegal to call main from inside your program. That means the only thing that is going to call it is the runtime and the compiler/linker can handle setting that up.This means you do not need a prototype for main.
A definition of a function also implicitly declares it. If you need to reference a function before it is defined you need to declare it before you use it.
So writing the following is also valid:
int sum(int x, int y) {
return x + y;
}
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
If you use a declaration in one file to make a function known to the compiler before it is defined, then its definition has to be known at linking time:
main.cpp
int sum(int x, int y);
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
sum.cpp
int sum(int x, int y) {
return x + y;
}
Or sum could have its origin in a library, so you do not even compile it yourself.
The main function is not used/referenced in your code anywhere, so there is no need to add the declaration of main anywhere.
Before and after your main function the c++ library might execute some init and cleanup steps, and will call your main function. If that part of the library would be represented as c++ code then it would contain a declaration of int main() so that that it could be compiled. That code could look like this:
int main();
int __main() {
__startup_runtime();
main();
__cleanup_runtime();
}
But then you again have the same problem with __main so at some point there is no c++ anymore and a certain function (main) just represents the entry point of your code.
Nope. You can't call it anyway.
You only need forward declarations for functions called before they are defined. You need external declarations (which look exactly like forward declarations on purpose) for functions defined in other files.
But you can't call main in C++ so you don't need one. This is because the C++ compiler is allowed to modify main to do global initialization.
[I looked at crt0.c and it does have a declaration for main but that's neither here nor there].
I'm a new programmer,my program is about getting LED on,maybe the simplest in C language,but it is always having _'Delay10ms':function contains unnamed parameter,hoping someone help me to solve it.
here are my words:
#include<reg51.h>
#include<intrins.h>
#define GPIO_LED P2
void Delay10ms(unsigned char time)
{
unsigned char i,j;
for(i=1;i<110*time;i++)
for(j=1;j<110;j++);
}
void main()
{
unsigned char n,i,j;
GPIO_LED=0X01;
while(1)
{
for(n=0;n<7;n++)
{
GPIO_LED=_crol_(GPIO_LED,1);
Delay10ms(50);
}
for(n=0;n<7;n++)
{
GPIO_LED=_cror_(GPIO_LED,1);
Delay10ms(50);
}
}
}
Either <reg51.h> or <intrins.h> probably have standard library includes. One of these library includes contains the standard header function time() that returns the current system time. Because your function parameter's name is time the IDE probably can't figure out what you meant with it and thus it gives you that error/warning. Try renaming your variable.
Also, the return type of main() has never been void (C++), use int.
It has been a Long time gone since I played c, but your code Looks o.k., maybe there is a name conflict ("time")
But there are some more questions:
- Why do you use char (unsigned char = 0..255) instead of classic int? This would be make code more readable.
- What do you expect how relyable your timer could be on a multitasking operating System?
I would implement such a function (if it not exists) as
void MyDelay (unsigned int delay_time)
{
start = MyOs.GiveMeTheTime()
while (MyOs.GiveMeTheTime() - start < delay_time)
{};
}
MyOs and GiveMeTheTime are names chosen by me. You must find out, which functions are available on your System, I am sure, they are.
I suppose, you try to program anything like a raspberry pi. Maybe this link could help:
Example Which Provides Accurate uS Timing
I am very new to programming and am confused about what void does, I know that when you put void in front of a function it means that "it returns nothing" but if the function returns nothing then what is the point of writing the function?? Anyway, I got this question on my homework and am trying to answer it but need some help with the general concept along with it. any help would be great, and please try to avoid technical lingo, I'm a serious newb here.
What does this function accomplish?
void add2numbers(double a, double b)
{
double sum;
sum = a + b;
}
void ReturnsNothing()
{
cout << "Hello!";
}
As you can see, this function returns nothing, but that doesn't mean the function does nothing.
A function is nothing more than a refactoring of the code to put commonly-used routines together. If I'm printing "Hello" often, I put the code that prints "Hello" in a function. If I'm calculating the sum of two numbers, I'll put the code to do that and return the result in a function. It's all about what you want.
There are loads of reasons to have void functions, some of these are having 'non pure' side effects:
int i=9;
void f() {
++i;
}
In this case i could be global or a class data member.
The other is observable effects
void f() {
std::cout <<"hello world" << std::endl;
}
A void function may act on a reference or pointer value.
void f(int& i) {
++i;
}
It could also throw, although don't do this for flow control.
void f() {
while(is_not_broke()) {
//...
}
throw std::exception(); //it broke
}
The purpose of a void function is to achieve a side effect (e.g., modify a reference parameter or a global variable, perform system calls such as I/O, etc.), not return a value.
The use of the term function in the context of C/C++ is rather confusing, because it disagrees wiht the mathematical concept of a function as "something returning a value". What C/C++ calls functions returning void corresponds to the concept of a procedure in other languages.
The major difference between a function and a procedure is that a function call is an expression, while a procedure call is a statement While functions are invoked for their return value, procedures are invoked for their side effects (such as producing output, changing state, and so on).
A function with void return value can be useful for its side effects. For example consider the standard library function exit:
void exit(int status)
This function doesn't return any value to you, but it's still useful for its side-effect of terminating the process.
You are on the right lines - the function doesn't accomplish anything, because it calculates something but that something then gets thrown away.
Functions returning void can be useful because they can have "side effects". This means something happens that isn't an input or output of the function. For example it could write to a file, or send an email.
Function is a bit of a missnomer in this case; perhaps calling it a method is better. You can call a method on an object to change its state, i.e. the values of it's fields (or properties). So you might have an object with properites for x and y coordinates and a method called Move which takes parameters xDelta and yDelta.
Calling Move with 2, 3 will cause 2 to be added to your X property and 3 to be added to your Y property. So the state of the object has changed and it wouldn't have made musch sense for Move to have returned a value.
That function achieves nothing - but if you had written
void add2numbers(double a, double b, double &sum)
{
sum = a + b;
}
It would give you the sum, whether it's easier to return a value or use a parameter depends on the function
Typically you would use a parameter if there are multiple results but suppose you had a maths routine where an answer might not be possible.
bool sqrt(double value, double &answer)
{
if value < 0.0 ) {
return false;
} else {
answer = real_sqrt_function(value);
return true;
}
}
I currently use a visualization library called VTK. I normally write void functions to update some part of the graphics that are displayed to the screen. I also use void functions to handle GUI interaction within Qt. For example, if you click a button, some text gets updated on the GUI.
You're completely right: calculating a function that returns nothing is meaningless – if you're talking about mathematical functions. But like with many mathematical concepts, "functions" are in many programming languages only related to mathematical functions, but behave more or less subtly different.
I believe it's good to explain it with a language that does not get it wrong: one such language is Haskell. That's a purely functional language which means a Haskell function is also a mathematical function. Indeed you can write Haskell functions much more mathematical-styled, e.g.
my_tan(x) = sin(x)/cos(x) -- or (preferred): tan' x = sin x / cos x
than in C++
double my_tan(double x) { return sin(x)/cos(x); }
However, in computer programs you don't just want to calculate functions, do you? You also want to get stuff done, like displaying something on your screen, sending data over the network, reading values from sensors etc.. In Haskell, things like these are well separated from pure functions, they all act in the so-called IO monad. For instance, the function putStrLn, which prints a line of characters, has type String -> IO(). Meaning, it takes a String as its argument and returns an IO action which prints out that string when invoked from the main function, and nothing else (the () parens are roughly what's void in C++).
This way of doing IO has many benefits, but most programming languages are more sloppy: they allow all functions to do IO, and also to change the internal state of your program. So in C++, you could simply have a function void putStrLn(std::string), which also "returns" an IO action that prints the string and nothing else, but does not explicitly tell you so. The benefit is that you don't need to tie multiple knots in your brain when thinking about what the IO monad actually is (it's rather roundabout). Also, many algorithms can be implemented to run faster if you have the ability to actually tell the machine "do this sequence of processes, now!" rather than just asking for the result of some computation in the IO monad.
Here goes newbie question number 5, but I don't have a teacher.. so.. anyhow here we go:
I'm wondering if is necessary to have function prototypes at the top of the file, instead of putting the main function to the end of the file and create all the function at the top of the file. As far as I can tell, VC++ and G++ both are not complaining. Is there standards that disallows me to do so?
It seems rather annoying to have to change the prototype when you change a function parameters and return types.
Example:
#include <iostream>
void say_hi(){
std::cout << "hi" << std::endl;
}
int main(){
say_hi();
return 0;
}
This declares but does not define the function say_hi:
void say_hi();
This both declares and defines the function say_hi:
void say_hi(){
std::cout << "hi" << std::endl;
}
You can declare a function many times; you can only define it once.
A function must be declared in the file before you can call it. A function must be defined somewhere--in the same file before or after you call it or maybe even in a different file.
So, yes, this is perfectly fine.
You are correct; if you define all your functions above where they are called, you don't need function prototypes. The actual function definition serves the same purpose as a separate declaration.
This works when you have tiny functions. It works less well when they get long. Or when you have more than one file of code. As a matter of style, many teachers demand that even tiny applications be written with the structure that serves large applications well.