'outchar', 'outint', but not 'outfloat' - c

I'm learning C because I have a book though it is as old as I am. I am using turboc++ and it works when I return 0; at the end of functions but I'm led to believe this was not always necessary. I am going through the exercises on functions.
outfloat will give me type mismatch in re-declaration of outfloat but the others work. What am I doing wrong?
#include "stdio.h"
main()
{
outchar('A');
outnum(2);
outfloat(3.3);
return 0;
}
outchar(char ch)
{
printf("%c",ch);
return 0;
}
outnum(int x)
{
printf("%d",x);
return 0;
}
outfloat(float z)
{
printf("%f",z);
return 0;
}

Since you don't provide a prototype for any of the functions used, the compiler assumes their parameters (and return type) are int.
For the first two functions that assumption "works".
For the last function, the assumption fails because the the parameter of type float is not compatible with (the assumed) type int.
Your best bet is to always provide prototypes for the functions you use. In the simple code you have you can use the fact that a function definition also serves as a prototype and move the definitions to before main().
#include <stdio.h>
/* prototypes */
int outchar(char ch);
int outnum(int x);
int outfloat(float z);
int main(void)
{
outchar('A');
outnum(2);
outfloat(3.3);
return 0;
}
int outchar(char ch)
{
printf("%c",ch);
return 0;
}
int outnum(int x)
{
printf("%d",x);
return 0;
}
int outfloat(float z)
{
printf("%f",z);
return 0;
}

Related

How does noNameFunc1 truly work here and how can I pass values to it?

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;
}

Invalid conversion from int* to int using functions

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.

unexpected output in c while returning nothing from an int returning function

#include <stdio.h>
int foo(int a)
{
int i;
for(i=2;i<=a;i++)
{
if(i%5==0)
{
return;
}
}
}
int main()
{
int c = foo(10);
printf("%d",c);
}
why is 5 getting printed when it is not even mentioned what to return?
#include <stdio.h>
int foo(int a)
{
int i;
for(i=2;i<=a;i++)
{
return; //no variable is attached with return
}
}
int main()
{
int c = foo(10);
printf("%d",c);
}
and this one is returning 2. which is the first value of i when the loop breaks due to return statement. but where is it mentioned that the function has to return i??
Code executed in Linux.
Not returning a value from a function designed to return an int invokes Undefined Behavior. Anything can happen. Quote from the C11 standard:
6.9.1 Function definitions
[...]
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
You're not returning an Integer in a method designed to return an Integer, there must be a catch that is returning the last integer created.
If you don't want to return anything, simply return void.

All the functions in c are globally defined, then why we need to pass them to function as argument?

In c, we have to define all the functions globally. while studying function pointer i got some program where programmer passes function name as parameter to other function. so why we need to pass function to other function if they all are globally defined?
here i am giving small sample program :
#include<stdio.h>
void bsort(int arr[],int n,int (*compare)(int,int)) //bubble sort
{
int i,j,temp;
for(i=0;i<n;i++){
for(j=0;j<n-i-1;j++){
if(compare(arr[j],arr[j+1]) > 0 ){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int compare(int a,int b)
{
if(a > b) return 1;
return -1;
}
void main()
{
int i;
int arr[5]={6,5,1,9,2};
bsort(arr,5,compare);
for(i=0;i<5;i++)
printf("%d ",arr[i]);
}
in this code, if we remove 3rd argument in definition and calling part of bsort function then also our program will give us same output.so for function pointer this program doesn't make sense.
can you please do some modification in this code and make it good example for function pointer.
Thanks.
Your code does not actual need passing functions as parameters. But your example is rather didactic to make you understand how function pointers work.
However it's important to understand them as they might become very useful especially when dealing with libraries loaded at runtime. There are tons of examples where function pointers are really a good tool.
Here's one:
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
double doOperation(double arg, double (*func)(double))
{
return (*func)(arg);
}
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
printf ("%f\n", doOperation(2.0, cosine);
dlclose(handle);
}
You open a library, search for the cosine function, and then pass it as an argument to doOperation.
You can also look here for more info.
Function pointers are used when you might need to change the behavior of your function call depending on some dynamic requirement.
This page sums it up short and sweet:
A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior. For instance, every time you need a particular behavior such as drawing a line, instead of writing out a bunch of code, all you need to do is call the function. But sometimes you would like to choose different behaviors at different times in essentially the same piece of code.
A few excellent examples are available there are well.
You pass a function [pointer] to another function because you want to dynamically direct which function the receiver calls. Or more precisely, because the receiver function is built to allow you to do so, thereby requiring you to do so. The pointed-to function does not need to be available at the time the receiver is compiled.
The comparison function required as a qsort() argument is the prototypical example.
Q: Why pass a function to another function?
Without re-writing bsort(), code can sort more than 1 way by only changing the compare function.
#include <stdio.h>
#include <stdarg.h>
int compare_up(int a,int b) {
if(a > b) return 1;
return -1;
}
int compare_down(int a,int b) {
if(a < b) return 1; // reverse the compare
return -1;
}
int compare_random(int a,int b) {
return rand() & 1; // mix them up
}
int main(void) {
int i;
int arr[5]={6,5,1,9,2};
bsort(arr,5,compare_up);
for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");
bsort(arr,5,compare_down);
for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");
bsort(arr,5,compare_random);
for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");
return 0;
}

Expected expression error in C

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;
}

Resources