This question already has answers here:
How do I assign an alias to a function name in C++?
(8 answers)
Closed 6 years ago.
The problem is something like:
I have a function named ADD_TWO(int,int);, now in the program, I want to create its alias keeping the previous function untouched. Something like ADD_TWO_NUMBERS(int,int);. i.e if I call ADD_TWO_NUMBERS it should execute ADD_TWO.
I want to have an Alias for the function.
int ADD_TWO(int a, int b)
{
return a+b;
}
int main()
{
int (*ADD_TWO_NUMBERS)(int, int) = ADD_TWO;
int result = ADD_TWO_NUMBERS(10, 12); //or (*ADD_TWO_NUMBERS)(10, 12)
cout<<" Result :- "<<result<<endl;
return 0;
}
Use Function pointers
Aside from using function pointers you can use function-like macros. Try something like
#define ADD_TWO_NUMBERS(x,y) ADD_TWO(x,y)
Since this question has c++ tag and assuming you're using a c++11 compiler, then:
int ADD_TWO(int a, int b)
{
return a+b;
}
int main()
{
auto ADD_TWO_NUMBERS = ADD_TWO;
int result = ADD_TWO_NUMBERS(10, 12);
cout << " Result :- " << result << endl;
return 0;
}
Related
This question already has answers here:
In a non-void function I want to return nothing
(2 answers)
When and how should I use exception handling?
(7 answers)
Closed 6 months ago.
Consider the following code:
#include <iostream>
int test(int a){
if (a > 10){
return a;
}
else{
std::cout << "Error!";
return nothing;
}
}
int main(){
std::cout << test(9);
return 0;
}
What I want is that The integer function test(int a), return a if a > 10, otherwise return Error!. but since this is an integer function, it must return an integer value, but I want that it print Error and return nothing. Is there a way for do this? (Also note that I don't want to use a void function)
#include <stdexcept>
int test(int a){
if (a > 10){
return a;
}
else{
throw std::invalid_argument( "a is smaller or eq than 10" );
}
}
This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Closed 2 years ago.
I was trying to calculate a factorial using recursion like this:
#include <iostream>
using namespace std;
int factorial(int a)
{
if(a == 0)
{
return 1;
}
return a*factorial(--a);
}
int main()
{
int a;
cin >> a;
cout << factorial(a) << endl;
return 0;
}
and it wasn't working. Then, I made a small change:
#include <iostream>
using namespace std;
int factorial(int a)
{
if(a == 0)
{
return 1;
}
return a*factorial(a-1);
}
int main()
{
int a;
cin >> a;
cout << factorial(a) << endl;
return 0;
}
... and it started working!
The problem is that I don't see any difference between these codes: Why didn't it work in the first code?
In your first code sample, the following line has undefined behaviour:
return a * factorial(--a);
This is because there is nothing in the C++ Standard that dictates whether or not the 'old' or 'new' (decremented) value of a is used to multiply the return value of the factorial function.
Compiling with clang-cl gives the following:
warning : unsequenced modification and access to 'a' [-Wunsequenced]
In your second code sample, there is no such ambiguity, as a is not modified.
I'm aware that when you write the call for your function you write it as displayArray(seasons,10)
with the name of one array and its size. I'm stuck on how you would right the arguments to pass the two arrays listed in my code, seasons and cartoons.
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
void displayArray(string car[], int sea[], int size);
int main()
{
int seasons[] = {5,10,8,2,12,7,31,9,3,4};
string cartoon[] = { "Steven Universe","Adventure Time","Regular Show","Gravity Falls",
"Spongebob Squarepants","Futurama","The Simpsons","Bob's Burgers","Avatar: The Last Airbender","Rick and Morty"};
displayArray() // Error Message here
}
void displayArray(string car[], int sea[], int size)
{
for (int x = 0; x < size; x++)
{
cout << " " << car[x] << "\t\t" << sea[x] << right << endl;
}
}
So you have to first create an array to pass your values with. Then just pass the array.
void function(int arr[]) {}
int arr[] = { 1, 2, 3, 4, 5 };
function(arr);
So in your code above, it should look like this:
int main()
{
int seasons[] = {5,10,8,2,12,7,31,9,3,4};
string cartoon[] = { "Steven Universe","Adventure Time","Regular Show","Gravity Falls",
"Spongebob Squarepants","Futurama","The Simpsons","Bob's Burgers","Avatar: The Last Airbender","Rick and Morty"};
displayArray(cartoon, seasons, 10);
}
Hope this helps :)
displayArray(cartoon, seasons, 5);
This seems to work fine for me. You just pass each array in according to whichever is declared first in the function argument list. Am I misunderstanding your question?
I'm learning C++ through Sololearn. Below is a code to find the largest of two numbers.
#include <iostream>
using namespace std;
int max(int a, int b){
if (a > b) {
return a;
}
return b;
}
int main() {
cout << max(7, 4) << endl;
return 0;
}
Result - 7
But shouldn't it return b also since there's return b in function????
Only one return statement will execute within a function. As soon as the code encounters the first return it will immediately leave the function and no further code will execute.
The answer of CoryKramer says it all.
Still, to avoid the confusion you bumped into, I would prefer:
#include <iostream>
using namespace std;
int max(int a, int b){
if (a > b) {
return a;
}
else {
return b;
}
}
int main() {
cout << max(7, 4) << endl;
return 0;
}
Alternatively you could use:
return a > b ? a : b;
The latter line is a so called 'conditional expression' (or 'conditional operator'). If the phrase before the ? is true, it returns the part between the ? and the :, else it returns the part after the : .
It is explained in detail here.
if (a > b) (7>4) ==> Condition becomes True so return a executed and max function return from there only, its not reach to return b, that's why its not execute return b.
You can use in return a > b ? a : b operator.
Operator return will
terminate the current function and returns the result of the expression to the caller
http://en.cppreference.com/w/cpp/language/return
After you passed the condition
if (a>b)
edited -> thanks to athul
return will evaluate a and put it as result of function.
If a is lesser then b - you will not meet this condition and you will hit
return b;
To understand it, you may add:
cout << max(2, 4) << endl;
cout << max(2, 1) << endl;
into the main section.
PS it is better to use at least codeblocks, which is advised in LearnC++ to enter their examples
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am studying for an exam and need your help.
I must write my own console terminal in C++, which must work in this way:
Example:
:>plus 5 7 "hit ENTER"
:>12
:>minus 10 12 "hit ENTER"
:>-2
:>combine Hello World "hit ENTER"
:>HelloWorld
:>run netstat "hit ENTER"
:>runs netstat
:>help
:>plus int1 int2
minus int1 int2
combine string1 string2
run ?????
:>exit
program exits
For main block I think it would be something like this
int main(void) {
string x;
while (true) {
getline(cin, x);
detect_command(x);
}
return 0;
}
The functions would be something like this
void my_plus(int a, int b) {
cout << a + b;
}
void my_minus(int a, int b) {
cout << a - b;
}
void my_combine(string a, string b) {
?????????????;
}
void my_run(?????????) {
???????????;
}
And the finally detect_command
void detect_command(string a) {
const int arr_length = 10;
string commands[arr_length] = { "plus", "minus", "help", "exit" };
for (int i = 0; i < arr_length; i++) {
if (a.compare(0, commands[i].length(), commands[i]) == 0) {
?????????????????????;
}
}
}
????? - means I don`t know what to write.
Help to make this program work.
Thanks.
I'm going to use the minus operation as an example...
Make a structure like so:
struct cmd_struct {
const char *name;
void (*func) (void *data);
};
Since your function parameters aren't the same, you gotta make a structure for each, e.g.:
struct minus_op {
int rhs;
int lhs;
};
And use the cmd_struct as an array, like so:
static cmd_struct commands[] = {
{ "minus", &my_minus },
...
};
my_minus would then be:
void my_minus(void *data) {
struct minus_op *mop = data;
... do the computation and return ...
}
And loop through it to detect the command used:
for (int i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i) {
if (strcmp(commands[i].name, a) == 0) {
... prepare the data ...
commands[i].func(data);
}
}
Side Note: In order to get the function parameters from command line, have a splitter, e.g. a white space. Use a vector for this and pass that vector to detect_command
Do also note: Get rid of the void param used in this example and use a char **argv and int argc like in main(). argv would be the arguments, and argc would be the number of arguments passed to the function. e.g. if you say to the program:
>> minus 5 1
Then argc should be 2 (the 5 and the 1) and argv[0] = "5" and argv[1] = "1".
Now that you know the idea behind it, implementing a more flexible version is left to you.
Call a respective function to handle each word. For example:
enum commands {
PLUS,
MINUS,
HELP,
EXIT
//....
};
int detect_command(string a) {
const int arr_length = 10;
string commands[arr_length] = { "plus", "minus", "help", "exit" };
for (int i = 0; i < arr_length; i++) {
if (a.compare(0, commands[i].length(), commands[i]) == 0)
return i;
}
return -1; //unknow word
}
Give the string to detect_command() the function return the respective integer to enum commands (that's our i value) or -1 if word is unknow. Then you can write a function like this to use and process the value determined by detect_command():
void run_command(int cmd)
{
switch(cmd) {
case PLUS: run_plus(); break;
case MINUS: run_minus(); break;
// and so on to all comamnds available
default: error("unknow command");
}
}
each function run_*() should continues the command parsing according to own rules, i.e, the "plus" command should be follow by one integer, one white-space and then another integer, right? run_plus() must validate it and then compute the result. e.g.:
//pseudo code
void run_plus()
{
//input here is one after "plus" word
//here we must validate our valid input: two digits split by a white-spaces
int x = parse_digit();
check(white-space);
int y = parse_digit();
int r = x + y;
display_result(r);
}
NOTE: I'm not a C++ programmer; I did detect_command() code modification to you get my idea. I even don't know if it will compile in C++ for the mismatch types.