When I compile the following C function / program I get errors like "missing ';' before 'type' 'remainder' : undeclared identifier" - what is wrong with this function?
#include <stdio.h>
void conversionTo(int number,int base) {
if(number==0)
return;
int remainder=number%base;
conversionTo((number/base),base);
if(remainder<10)
printf("%c",'0'+remainder);
else
printf("%c",'a'-10+remainder);
}
int main() {
conversionTo(int number,int base);
return 0;
}
I'm not a C expert, but from experience very long ago I believe you cannot declare variables in the middle of a function.
Also, it's unclear what you are trying to do with the function / print statements.
Try this:
#include <stdio.h>
void conversionTo(int number,int base) {
int remainder=number%base;
if(number==0)
return;
conversionTo((number/base),base);
if(remainder<10)
printf("%c",'0'+ remainder); // Through the way ASCII works that gives the ASCII rep
// of the remainder.
else
printf("%c",'a'-10+remainder); // Hex digits (A-F).
}
int main() {
conversionTo(/*Any number here*/10, /*any base number here*/2);
return 0;
}
You need to defines variables, then they can be used.
So this:
int main() {
conversionTo(int number,int base);
return 0;
}
should become this:
int main(void)
{
int number;
int base:
number = 47;
base = 11;
conversionTo(number, base);
return 0;
}
Also non C99 compliant compilers do not like having variables declared in the middle of a context:
void conversionTo(int number,int base) {
if(number==0)
return;
int remainder=number%base; /* this would fail. */
conversionTo((number/base),base);
To get around this open another context:
void conversionTo(int number,int base) {
if(number==0)
return;
{
int remainder=number%base;
conversionTo((number/base),base);
if(remainder<10)
printf("%c",'0'+remainder);
else
printf("%c",'a'-10+remainder);
}
}
You have to invoke your function with a value or variable, not a declaration:
conversionTo(123, 10); // using constant value
or
int number = 123, base = 10; // variable declaration
conversionTo(number, base); // using variable
You are calling your function wrong - pass the arguments this way:
conversionTo(2,2); // assuming you want to convert 2 to binary
or
int number = 123, base = 10;
conversionTo(number, base); // note this is not the same number and base as in the definition of your conversionTo function
Full code:
#include <stdio.h>
void conversionTo(int number,int base)
{
if(number==0)
return;
int remainder=number%base;
conversionTo((number/base),base);
if(remainder<10)
printf("%c",'0'+remainder);
else
printf("%c",'a'-10+remainder);
}
int main()
{
conversionTo(2,2); // assuming you want to convert 2 to binary
return 0;
}
There are 3 things when using functions:
Function declaration / prototype - the prototype of your function is:
void conversionTo(int ,int );
Function definition:
void conversionTo(int number,int base /* Parameter list*/)
{
// your functionality
}
Function call where you pass your arguments to your function:
conversionTo(2,2);
The statement conversionTo(int number,int base); simply re-declares it. Try this even this will compile:
int main()
{
printf("Hello World");
int main();
}
conversionTo(int number, int base)
is the syntax for declaring which parameters the function can take. To actually call the function, you need to omit the type (assuming you have variables of the respective name)
int number = 5;
int base = 10;
conversionTo(number, base); // <-- no int here!
Or you can use numbers directly:
conversionTo(5, 10);
Your function definition number and base in your function declaration void conversionTo(int number, int base) are the names that the values passed to it will have inside the function. So, if you call conversionTo(2,5), 2 will be seen inside the function as number, while 5 will be seen as base.
If you want to use variables instead of contants to call the function, you could do that:
int main()
{
int base = 2;
int number = 5;
conversionTo(base, number);
return 0;
}
In this confusing example, the variables base and value have value 2 and 5, respectively. But as you pass them to the function, the values inside it will be number = 2 and base = 5. This shows that those variables are actually different, despite of having the same name.
You should compile with $CC -std=c99, to enable declaring variables in the middle of a block.
(see section 6.8 in the specification)
The declaration "int remainder" must come before any statements in a block.
A declaration may have an initializer as you have here.
You could do:
void conversionTo(int number,int base) {
if (number > 0) {
int remainder...
}
}
since the function will not work with negative numbers.
To fix the other bugs in the routine:
void conversionTo(int number,int base)
{
if(number>=0&&base>0&&base<=36)
{
int remainder=number%base;
number/=base;
if(number>0)conversionTo(number,base);
printf("%c",(remainder<10)?'0'+remainder:'a'+remainder-10);
}
}
This will print a 0 if number is zero and only recurse if needed.
Related
I have this code for finding the factorial of a number, and there's an implicitly declared function noNameFunc2 in the return value of the first function noNameFunc1.
How can I pass values to the first function without running into the error: undefined reference to `noNameFunc2'?
All I'm trying to understand is how control is being passed between the two functions.
I pass values to noNameFunc2() and it works as it should. noNameFun1() is really just a check for whether input is 0 or nah.
#include <stdio.h>
int noNameFunc1(int);
int noNameFunc2(int, int);
int main() {
int noNameFunc1(int n){
if (n==0){
return 1;
}
return noNameFunc2(n, 1);
}
int noNameFunc2(int c, int s) {
if (c == 1) {
return s;
} else {
return noNameFunc2(c - 1, s * c);
}
}
printf("%d", noNameFunc2(5,1));
return 0;
}
If I edit the printf statement to printf("%d", noNameFunc1(5)); there's an error: undefined reference to `noNameFunc2'
Why does this crop up and can I pass values to noNameFunc1() at all?
You have defined the functions inside main. This is an example of nested functions.
These are not allowed in the C standard, but some compilers offer it as a GCC-compatible extension (so GCC provides them, and so does Clang).
What you should do is to have the function definition outside of the main function. This will allow both functions to be seen by the compiler.
#include <stdio.h>
int noNameFunc1(int);
int noNameFunc2(int, int);
int noNameFunc1(int n){
if (n==0){
return 1;
}
return noNameFunc2(n, 1);
}
int noNameFunc2(int c, int s) {
if (c == 1) {
return s;
} else {
return noNameFunc2(c - 1, s * c);
}
}
int main() {
printf("%d", noNameFunc2(5,1));
return 0;
}
I learning C for 1 years, i saw a type of defining a function. I couldn't name it, so i want to know the name of the defining function.
We defining functions as standard:
FunctionReturnType FunctionName(FunctionArgs)
{
codes();
}
But i saw that type:
FunctionReturnType FunctionName(FunctionArgs)(TheWeirdArea)
{
codes();
}
So what we doing for in i named as TheWeirdArea? I guess it's relative with function arguments, but i want to know correctly what we do in TheWeirdArea.
I guess this is about returning a function pointer to a function looking like
FunctionReturnType func(TheWeirdArea);
Here is an example:
#include <stdio.h>
int bar1(int b)
{
printf("bar1\n");
return 42 + b;
}
int bar2(int b)
{
printf("bar2\n");
return 100 + b;
}
int (*foo(int a))(int b) // Returns a function pointer
{
if (a == 1) return bar1;
return bar2;
}
int main(void) {
printf("%d\n", foo(1)(100));
printf("%d\n", foo(2)(200));
return 0;
}
Output:
bar1
142
bar2
300
Hope this dummy example help you
int add(int x,int y)
{
return x+y; //very dummy function return x+y
}
typedef int (*pointer_to_add)(int,int);
/* this is a declaration of function pointer works
with any function has an int return type and
accept two int arguments not only add */
int (*my_function(int arg1, double arg2))(int, int)
{
/*This a function accept an int argument
arg1 and double arg2 and return pointer to a function or address of function
which has a two int type arguments and return an int */
pointer_to_add ptr=add; //ptr is a pointer now to add function.
return ptr;
}
More simple form
pointer_to_add my_function(int arg1,double arg2)
{
pointer_to_add ptr=add;
return ptr;
}
Now in your main code you can use the returned address like:
int main(void)
{
pointer_to_add P=my_function(25,3.5);
printf("%i",p(22,33));
return 0;
}
I am trying to code the printf function. The problem is that my code is getting very messy and I need some help to try to make it organized and working (hopefully). I have been told that I should use "array of function pointers" so I tried below (ft_print_it) as you can see but I do not know how to how to structure my code so that I can use a big array of function pointer to put every function like int_decimal_octal and friends. Can you help me on that? Where can I call them from?
Also, I realized the little function below (cast_in_short) is giving me the same result as printf if I write the output with my ft_putnbr. My second question is thus: Can I make my printf work with little functions like this? Thank you so much.
int cast_in_short(int truc)
{
truc = (short)truc;
return (truc);
}
/*
here in the main I noticed that I get the same behaviour
between my putnbr and printf thanks to my little function
cast_in_short. This is the kind of function I want to use
and put into an array of pointer of functions in order
to make my printf work
*/
int main()
{
int n = 32769;
n = cast_in_short(n);
ft_putnbr(n);
printf("\n");
return (0);
}
/* function to launch ft_print_it */
int ft_print_str_spec(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putstr(va_arg(ap, char *));
else
{
ft_nbzero(ap, flag, 0);
ft_putstr(va_arg(ap, char *));
}
return (1);
}
int ft_print_oct(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putnbr(decimal_octal((va_arg(ap, int))));
else
{
ft_nbzero(ap, flag, 1);
ft_putnbr(decimal_octal((va_arg(ap, int))));
}
return (1);
}
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
char *ft_strjoin2(char const *s1, char const c);
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
int decimal_octal(int n) /* Function to convert decimal to octal */
{
int rem;
int i;
int octal;
i = 1;
octal = 0;
while (n != 0)
{
rem = n % 8;
n /= 8;
octal += rem * i;
i *= 10;
}
return (octal);
}
I think the best way to organize your code to avoid the function like your "flag_code" is to use an array of structure. With structure that contain a char (corresponding to the flag) and a function pointer.
For example :
typedef struct fptr
{
char op;
int (*ptr)(va_list);
} fptr;
And instatiate it like that (with { 'flag', name of the corresponding function} ) :
fptr fptrs[]=
{
{ 's', ft_print_nb_spec },
{ 'S', ft_print_nb_up },
{ 0, NULL }
};
Then when you know have char after the % (the flag) you can do something like this :
int i = -1;
while (fptrs[++i].op != flag && fptrs[i].op != 0);
if (fptrs[i].op != 0)
{
fptrs[i].ptr();
}
For exemple if flag = 'S' the while loop will stop when i = 1 and when you call fptrs[1].ptr() you will call the corresponding function in the structure.
I think instead of making your code messy by using function pointers, because in the end you cannot specialize printf function without providing the format, in C there is no function overloading or template functions. My suggestion is to special printf function by type.
// print seperator
void p (int end)
{ printf(end?"\n":" "); }
// print decimal
void pi (long long n)
{ printf("%lld",n); }
// print unsigned
void pu (unsigned long long n)
{ printf("%llu",n); }
// print floating point
void pf (double n)
{ printf("%g",n); }
// print char
void pc (char n)
{ printf("%c",n); }
// print string
void ps (char* n)
{ printf("%s",n); }
Test try here
pi(999),p(0),pf(3.16),p(0),ps("test"),p(1);
Output
999 3.16 test
Another option
In theory you can define polymorphic print function in a struct, in case you can do something like this. I haven't tested this yet.
struct Node
{
enum NodeType {Long,Double,Char,String} type;
union {long l,double d,char c,char* s};
};
void p(Node* n)
{
switch (n->type)
{
case Node::NodeType::Long: printf("%ld", n->l);
case Node::NodeType::Double: printf("%g",n->d);
case Node::NodeType::Char: printf("%c",n->c);
case Node::NodeType::String: printf("%s",n->s);
}
}
I have this "simple" problem: I have in input 2 int numbers and i must output them in decreasing order.
#include <stdio.h>
#include <iostream>
int fnum()
{
int NUM;
scanf("%d",&NUM);
return NUM;
}
void frisultato(int x,int y)
{
if (x>y)
{
printf("%d",x);
printf("%d",y);
}
else
{
printf("%d",y);
printf("%d",x);
}
return;
}
int main()
{
int A,B;
A=fnum;
B=fnum;
frisultato(A,B);
}
I recieve an error at
A=fnum;
B=fnum;
my compiler says: invalid conversion from int(*)() to int.
This is the first time i use functions, what is the problem? Thank you!
Michelangelo.
A=fnum;
B=fnum;
You're not actually calling the function fnum here. You're attempting to assign a pointer to the function to the int variables A and B.
To call the function, do this:
A=fnum();
B=fnum();
Sorry, but since you seem to be new at programming, I couldn't help but refactor/comment on your code:
#include <stdio.h>
#include <iostream>
int fnum()
{
int num;
scanf("%d",&num);
return num;
}
void frisultato(int x, int y)
{
if (x>y)
{
printf("%d",x);
printf("%d",y);
}
else
{
printf("%d",y);
printf("%d",x);
}
/* No need to return in void */
}
int main()
{
/*
Variables in C are all lowercase.
UPPER_CASE is usually used for macros and preprocessor directives
such as
#define PI 3.14
*/
int a, b;
a = fnum(); //Function calls always need parenthesis, even if they are empty
b = fnum();
frisultato(a, b);
/*
Your main function should return an integer letting whoever
ran it know if it was successful or not.
0 means everything went well, anything else means something went wrong.
*/
return 0;
}
Also, don't sign your name on StackOverflow questions.
I'm trying to create two functions. The first function accepts integer inputs from the user until they are between 0 and 100. The seconds function display the validation to the stdOut.
However, it keeps giving me an error saying "Expected expression" when I call the function.
#include <stdio.h>
// function prototype for the function input
int input(int);
// function prototype for the function validate
int validate(int);
//main function
int main(void)
{
//calling the function input
input(int x)
//calling the function validate
validate(int y)
return 0;
}
// Function definition for input
int input(int a)
{
int r;
printf("Enter the int value of r\n");
scanf("%d",&r);
}
// Function definition for validate
int validate(int b)
{
int r;
if(r>= 0 && r<= 100)
printf("Valid number");
else
printf("Invalid");
}
There is at least one bug on almost every line of this program.
This is a standard problem for which there is a whole lot of incorrect advice out there (most importantly, only the strtol/strtoul/strtod family of functions should be used to convert strings to numbers; never use the atoi family and never use scanf) so I am going to give a complete worked example of how to write this program correctly, including proper use of comments.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
long read_number_in_range(const char *prompt, long lo, long hi)
{
// a signed 64-bit number fits in 21 characters, +1 for '\n', +1 for NUL
char buf[23], *endp;
long rv;
for (;;) {
puts(prompt);
if (!fgets(buf, sizeof buf, stdin)) {
perror("stdin");
exit(1);
}
errno = 0;
rv = strtol(buf, &endp, 10);
if (endp != buf && (*endp == '\0' || *endp == '\n')
&& !errno && rv >= lo && rv <= hi) {
return rv;
}
// if we get here, fgets might not have read the whole line;
// drain any remainder
if (!strchr(buf, '\n')) {
int c;
do c = getchar();
while (c != EOF && c != '\n');
}
puts("?Redo from start");
}
}
int main(void)
{
long val = read_number_in_range("Enter the int value of r", 0, 100);
// do something with val here
return 0;
}
Read on for line-by-line nitpicking of the original program.
#include <stdio.h>
Correct.
// function prototype for the function input
Comment redundant with code.
int input(int);
Function signature incorrect (see comments on body of function).
// function prototype for the function validate
Comment redundant with code.
int validate(int);
Function signature incorrect (see comments on body of function).
//main function
Comment redundant with code.
int main(void)
{
Correct.
//calling the function input
Comment redundant with code.
input(int x)
Variables cannot be declared inside function call expressions.
Return value of function is ignored.
Missing semicolon at end of line.
//calling the function validate
Comment redundant with code.
validate(int y)
Value returned from input should be passed to validate, presumably, instead of a new uninitialized variable.
Variables cannot be declared inside function call expressions.
Return value of function is ignored.
Missing semicolon at end of line.
return 0;
}
Correct.
// Function definition for input
Comment redundant with code.
int input(int a)
{
Parameter a is unnecessary.
int r;
Correct.
printf("Enter the int value of r\n");
Minor: use puts when there is nothing to format.
scanf("%d",&r);
Never use scanf.
}
Missing return r;.
// Function definition for validate
Comment redundant with code.
int validate(int b)
{
Function has no return value, so should be void validate(int b).
int r;
Unnecessary variable.
if(r>= 0 && r<= 100)
r should be b on this line.
printf("Valid number");
else
printf("Invalid");
Minor: again, puts.
}
Correct.
You have some stray ints in your calls, they need to go.
The calls should probably be:
x = input();
validate(x);
You can't pass an integer to a function and expect it to change in the caller's context, that is not how C's pass-by-value semantics work. You should just return the number from input() instead, i.e. its prototype should be int input(void);.
You need to add semicolons at the end of each line of code in your main() function, and also remove the type specifier in the function calls. Also, don't forget to declare the variables x and y somewhere:
int main(void)
{
int x=0;
int y=0;
//calling the function input
input(x);
//calling the function validate
validate(y);
return 0;
}
I bet the compiler asks you for an expression in some place where you write a function declaration with a missing semicolon.
//calling the function input
input(int x)
//calling the function validate
validate(int y)
Neither of these is a function call.
#include <stdio.h>
int input(int*);
int validate(int);
int main(void){
int x;
input(&x);
if(validate(x))
printf("Valid number");
else
printf("Invalid");
return 0;
}
int input(int *r){
printf("Enter the int value of r\n");
scanf("%d", r);
return *r;
}
int validate(int r){
return r>= 0 && r<= 100;
}