Keeps saying that there is an expected expression before double int pt function
#include <stdio.h>
int pt (int a, int b)
{
int c, result;
c = (a * a) + (b + b);
result = double sqrt (double c);
return result;
}
int main (void)
{
int d, e, f;
int pt (int a, int b);
printf("type enter after input of the two legs");
scanf("%i", &d);
scanf("%i", &e);
f = pt (d,e);
printf("the hypotenuse is %i", f);
return 0;
}
Change
result = double sqrt (double c);
to
result = sqrt(c);
You don't have to cast c into a double when you pass it into the sqrt function because of implicit conversion. If you still wanted to do the cast, the correct way would be sqrt((double) c).
Also, #include <math.h> for use of the sqrt function.
Note: It's not required to cast the return type of sqrt to int (relevant since result is of type int) - however some compilers may give warnings about implicit conversion (Credit to #MattMcNabb). It can also be good practice to put the cast in to signal to other coders that the precision loss is intentional.
double sqrt (double c); is a function declaration. (It is also a function prototype). This is how you announce that a function exists, and what parameters it takes and what it returns. The word c here does not mean anything, it can be omitted.
When you want to call a function you do not repeat this info. You just give the function name, followed by a list of values, e.g. sqrt(c) .
In your code , sqrt has not been declared. Functions must be declared before they are called. It's not possible to simultaneously declare a function and call it; you have to declare it first.
(Historical note: this is true from C99 onwards; in C89 you could call an undeclared function, and the compiler would assume you wanted the function declared to return int ; this would cause undefined behaviour for any function that does not actually return int).
It is possible for you to provide your own declaration, so long as it matches the standard declaration:
double sqrt(double);
However it is a better idea to just use the standard declaration by going:
#include <math.h>
which works because the file math.h includes the line double sqrt(double); (or something equivalent).
Then you can write:
result = sqrt(c);
Note that you do not need to use any casts in relation to this function call. Since a function prototype exists, the compiler knows that even if you supply an int, it should convert that int to a double (which it knows how to do), and vice versa.
It is talking about the casting that you are doing?
your casting is complaining it should be like this:
your result is an integer, so you should be casting it to int..
but if you want to cast anything to double it should be as follow
result = (double)sqrt((double) c)
or another way is double(sqrt((double) c)
but if you want to cast it as int then
result = (int)sqrt((double) c)
or
result = int(sqrt((double) c))
hope this helps good luck
Related
#include <stdio.h>
int main() {
foo(22.3);
return 0;
}
void foo(int x) {
printf("%d", x);
}
Prints 1. Why isn't it printing 22 instead? I believe that when I call foo without declaring an explicit prototype, c generates an implicit prototype that converts short and char to int, and float to double in the function arguments. So 22.3 isn't touched in the call to foo(22.3) and then in the callee function, the parameter int x gets assigned to 22.3: int x = 22.3 which results in numeric conversion wherein the fractional part gets dropped, leaving just 22 in x. So why isn't it printing 22 instead of 1 ?
I think I've got it wrong as to what happens when a caller calls a callee, with mismatched parameter types?
You're calling a function with parameters that are not compatible with the arguments. Because the function doesn't have a prototype, the double-to-int conversion doesn't occur. This results in undefined behavior.
If you were to pass an int, or a smaller integer type that would be promoted to int, then the function would work.
You forgot about function prototype:
#include <stdio.h>
void foo(int); // <--- here!
int main() {
foo(22.3);
return 0;
}
void foo(int x) {
printf("%d", x);
}
Without this, the compiler probably takes bytes from the beginning of your float value 22.3 and treats them as integer value.
#include<stdio.h>
int main(){
int ret = 0;
ret = func(1.0,2.0);
printf("\n ret : %d \n",ret);
return 0;
}
func(int a,int b){
float m = 5.0;
float n = 6.0;
int sum = m + n;
printf("\n sum : %d \n",sum);
return a+b;
}
EDITED
sum : 11
ret : -877505847
why the float value passed to the integer throws a garbage value while the float value added and assigned to an integer inside the function gives the correct value 11 ?
You need to provide a declaration for func before calling it
int func(int a,int b);
int main() {
}
int func(int a,int b) {
// implementation
}
Your code presumably compiled with a warning something like warning: implicit declaration of function 'func'. If you'd fixed this warning, you'd also have fixed the error.
It'd be good practice to have the compiler warn you about as many potential problems as possible. You may also want to guard against the possibility of missing warnings by treating them as errors. You can do this by adding -Wall -Werror to your build command for gcc or /W4 /Wx for MSVC.
Note that the correct value is returned if you pass ints into func. At a guess, this may be because the calling code doesn't know that it needs to cast the arguments to int and passes float instead. func then either reads registers/stack locations that floats weren't copied to or receives the bit representations of float arguments and treats them as int. Either of these will result in incorrect values of a, b being received. You can check this yourself by adding a printf inside func to note the values of its arguments.
I have created an array of function pointers to swap two variables.
pointer pointing to these functions namely: swap1, swap2. swap3 and swap4.
swap2 is swaping using pointer passed as arguments.
but while declaring the function pointer, only int and int are passed as arguments. after compiling this causes many warnings.
so do we have a better way of passing the argument, where we put condition in function call itself.
code is given below.
#include <stdio.h>
int swap1(int ,int );
int swap2(int* ,int* );
int swap3(int ,int );
int swap4(int, int);
int swap1(int a,int b)
{
int temp=a;
a=b;
b=temp;
printf("swapped with 3rd variable :%d, %d\n", a,b);
}
int swap2(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
printf("swapped with pointer :%d, %d\n", *a,*b);
}
int swap3(int a,int b)
{
a+=b;
b=a-b;
a-=b;
printf("swapped with 2 variable :%d, %d\n", a,b);
}
int swap4(int a,int b)
{
a=a^b;
b=a^b;
a=a^b;
printf("swapped with bitwise operation :%d, %d\n", a,b);
}
int main()
{
int ch;
int a=3;
int b=4;
printf("enter the option from 0 to 3\n");
scanf("%d",&ch);
int (*swap[4])(int, int) ={swap1,swap2,swap3,swap4};// function pointer
/*can we pass something like int(*swap[4]( condition statement for 'pointer to variable' or 'variable')*/
if (ch==1)// at '1' location, swap2 is called.
{
(*swap[ch])(&a,&b);//passing the addresses
}
else
{
(*swap[ch])(a,b);
}
return 0;
}
some warnings are as follows.
at line 36 in file '9e748221\script.c'
WARNING: found pointer to int where int is expected
at line 47 in file '9e748221\script.c'
WARNING: found pointer to int where int is expected
at line 47 in file '9e748221\script.c'
Well yes. There are a number of problems with your code, but I'll focus on the ones to which the warnings you presented pertain. You declare swap as an array of four pointers to functions that accept two int arguments and return an int:
int (*swap[4])(int, int)
Your function swap2() is not such a function, so a pointer to it is not of the correct type to be a member of the array. Your compiler might do you a better favor by rejecting the code altogether instead of merely emitting warnings.
Having entered a pointer to swap2() into the array anyway, over the compiler's warnings, how do you suppose the program could call that function correctly via the pointer? The type of the pointer requires function arguments to be ints; your compiler again performs the dubious service of accepting your code with only warnings instead of rejecting it.
Since the arguments in fact provided are the correct type, it might actually work on systems and under conditions where the representations of int and int * are compatible. That is no excuse, however, for writing such code.
Because pointers and ints are unchanged by the default argument promotions, one alternative would be to omit the prototype from your array declaration:
int (*swap[4])() = {swap1,swap2,swap3,swap4};
That says that each pointer points to a function that returns int and accepts a fixed but unspecified number of arguments of unspecified types. At the point of the call, the actual arguments will be subject to the default argument promotions, but that is not a problem in this case. This option does prevent the compiler from performing type checking on the arguments, but in fact you cannot do this correctly otherwise.
Your compiler might still warn about this, or could be induced to warn about it with the right options, but the resulting code nevertheless conforms and does the right thing, in the sense that it calls the pointed-to functions with the correct arguments.
To deal with the warnings first: You declare an array of functions which take int parameters. This means that swap2 is incompatible with the type of element for the array you put it in. This will generate a diagnostic.
Furthermore, when you call one of the functions in the array, the same array declaration tells the compiler that the parameters need to be ints not pointers to int. You get two diagnostics here, one for each parameter.
To fix the above all your functions need to have compatible prototypes with the element type of the array. Should it be int or int*? This brings us to the other problem.
C function arguments are always pass by value. This means that the argument is copied from the variable onto the stack (or into the argument register depending on the calling convention and argument count - for the rest of this post, I'll assume arguments are placed on the stack for simplicity's sake). If it's a literal, the literal value is put on the stack. If the values on the stack are changed by the callee no attempt is made by the caller, after the function returns, to put the new values back in the variables. The arguments are simply thrown away.
Therefore, in C, if you want to do the equivalent of call by reference, you need to pass pointers to the variables you use as arguments as per swap2. All your functions and the array should therefore use int*. Obviously, that makes one of swap1 and swap2 redundant.
The correct array definition is
int (*swap[4])(int*, int*) = {swap1, swap2, swap3, swap4};
and the definition of each function should be modified to take int* parameters. I'd resist the temptation to use int (*swap[4])() simply because it circumvents type safety. You could easily forget the & in front of an int argument when the called function is expecting a pointer which could be disastrous - the best case scenario when you do that is a seg fault.
The others have done great work explaining what the problems are. You should definitely read them first.
I wanted to actually show you a working solution for that sort of problem.
Consider the following (working) simple program :
// main.c
#include <stdio.h>
void swap1(int* aPtr, int* bPtr) {
printf("swap1 has been called.\n");
int tmp = *aPtr;
*aPtr = *bPtr;
*bPtr = tmp;
}
void swap2(int* aPtr, int* bPtr) {
printf("swap2 has been called.\n");
*aPtr += *bPtr;
*bPtr = *aPtr - *bPtr;
*aPtr -= *bPtr;
}
int main() {
int a = 1, b = 2;
printf("a is now %d, and b is %d\n\n", a, b);
// Declare and set the function table
void (*swapTbl[2])(int*, int*) = {&swap1, &swap2};
// Ask for a choice
int choice;
printf("Which swap algorithm to use? (specify '1' or '2')\n>>> ");
scanf("%d", &choice);
printf("\n");
// Swap a and b using the right function
swapTbl[choice - 1](&a, &b);
// Print the values of a and b
printf("a is now %d, and b is %d\n\n", a, b);
return 0;
}
First of, if we try to compile and execute it:
$ gcc main.c && ./a.out
a is now 1, and b is 2
Which swap algorithm to use? (specify '1' or '2')
>>> 2
swap2 has been called.
a is now 2, and b is 1
As myself and others mentioned in answers and in the comments, your functions should all have the same prototype. That means, they must take the same arguments and return the same type. I assumed you actually wanted to make a and b change, so I opted for int*, int* arguments. See #JeremyP 's answer for an explanation of why.
I am sure I'm missing something obvious here but just can't figure out what it is. In my repository, I have a file called ddpoly_2.c which contains a function called "ddpoly2". I call this function from the main function in tst5.c. If you look at the code in tst5_2.c, I am assigning to x a value of 2, immediately printing it and then passing it to "ddpoly2" as the third argument (which is as per what the calling pattern should be like as far as I can tell). I then immediately print x from within the function "ddpoly2". What I see is the following:
x outside: 2.000000
x inside : 0.000000
nc: 2
nd: 3
You can see that x was 2.000000 just before the function was called but it became 0.0000000 once inside the function. I must be missing something overtly obvious here but can't figure out what it is.
P.S. I compile the code using the makefile in the same directory.
EDIT: Including relevant parts of code here.
Calling the function in tst5_2.c:
int main(int argc, char *argv[])
{
//Used to determine which section gets its results printed.
float c[] = {1,1,1,0,0};
int nc = 2;
float x = 2.0;
float pd[] = {0,0,0,0,0};
int nd = 3;
printf("x outside: %f\n",x);
ddpoly2(c,nc,x,pd,nd);
}
printing it inside the function ddpoly2:
#include <stdio.h>
void ddpoly2(float c[], int nc, float x, float pd[], int nd)
{
int nnd, j, i;
float cnst = 1.0;
printf("x inside : %f\n",x);
printf("nc: %d\n",nc);
printf("nd: %d\n",nd);
}
You're calling a function without a prototype. This is illegal since 1999 but your compiler is helpful and allows this as a compatibility with old C standards.
The C standard says:
If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double.
The correct solution is to:
Always have correct function prototypes.
Always enable all warnings in compilation and treat them as errors.
Ok so, I'm trying to write a program which numerically evaluates integrals using Simpson's 3/8 rule. I'm having issues passing the values from Integral *newintegral to the simpson() function. I'm not massively confident in my understanding of structures and pointers, and I've been reviewing the lecture notes and checking online for information all day and I still can't understand why it's not working.
At the moment when I try to build my program it comes up with a number of errors, particularly: on line 46 "expected expression before Integral" and on most of 55-63 "invalid type of argument of '->' (have 'Integral') I don't understand why the first one is occurring because all my lecturers examples of this type of thing, when passing a structure to a function just have the syntax func(Struct_define_name individual_struct_name). I thought this is what I was doing with mind (Integral being the name of the structure type and i being the specific structure) but obviously not.
I think these two problems are connected so I included all of my code for context, however the lines which actually have errors are 46 and 55-63 as mentioned above. I've probably defined the structure wrong in the first place or something though.
(Incidentally the maths in the simpson() function doesn't actually work properly now anyway, but that's not something I'm concerned about)
Also I tried looking at other similar questions but I didn't understand what the other code was doing so I couldn't extrapolate how to fix my code from that. I know this isn't very relevant to other people but I really don't understand programming well enough to try and phrase my question in a general sense...
'#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct integral {
double result, limits[2];
int degree;
double coefficients[];
} Integral;
// Prototype of function that calculates integral using Simpson's 3/8 rule
double simpson(Integral i);
// function (?) which initialises structure
Integral *newintegral() {
Integral *i = malloc(sizeof *i);
double lim1_in, lim2_in;
int degree_input, n;
printf("Please enter the degree of the polynomial.\n");
scanf("%d", °ree_input);
i->degree = degree_input;
printf("Please enter the %d coefficients of the polynomial, starting\n"
"from the highest power term in the polynomial.\n", (i->degree+1));
for (n=i->degree+1; n>0; n=n-1) {
scanf("%lg", &i->coefficients[n-1]);
}
printf("Please enter the upper limit of the integral.\n");
scanf("%lg", &lim1_in);
i->limits[0] = lim1_in;
printf("Please enter the lower limit of the integral.\n");
scanf("%lg", &lim2_in);
i->limits[1] = lim2_in;
return i;
}
int main() {
Integral *i = newintegral();
simpson(Integral i);
return 0;
}
double simpson(Integral i) {
int n;
double term1, term2, term3, term4;
for (n=(i->degree); n>0; n=n-1) {
term1=(pow(i->limits[1],n)*(i->coefficients[n]))+term1;
term2=(pow(((((2*(i->limits[1]))+(i->limits[0])))/3),n)*(i->coefficients[n]))+term2;
term3=(pow(((((2*(i->limits[0]))+(i->limits[1])))/3),n)*(i->coefficients[n]))+term3;
term4=(pow(i->limits[0],n)*(i->coefficients[n]))+term4;
}
i->result = (((i->limits[0])-(i->limits[1]))/8)*(term1+(3*term2)+(3*term3)+term4);
printf("The integral is %lg\n", i->result);
return 0;
}'
You're currently passing a pointer to a function that takes a single Integral argument.
Your prototype, double simpson(Integral i); tells the compiler "declare a function called simpson that returns a double and takes a single Integral referenced by the identifier i inside the function.
However, in main() you say:
int main() {
//declare a pointer to an Integral and assign it to the return of 'i'
Integral *i = newintegral();
//call the function simpson with i.
//However, you are redeclaring the type of the function argument, so the compiler will complain.
simpson(Integral i);
return 0;
}
Your call, simpson(Integral i); will not work because you are redeclaring the type of the function argument. The compiler will state:
:46:13: error: expected expression before ‘Integral’
What you really need is for simpson() to take a pointer to Integral as its argument. You have actually already handled this inside the function, (using i->) but your function prototype is telling the compiler that you are passing the whole struct Integral as the function argument.
Solution:
Change your function prototype as follows:
double simpson(Integral *i); // function returning double taking single pointer to an Integral named i.
...and change main() to look like the following:
int main(void) { //In C main has two valid definitions:
//int main(void), or int main(int argc, char **argv)
Integral *i = newintegral();
simpson(i);
return 0;
}
So in conclusion, your understanding of pointers is correct, but not how you pass a pointer to a function.
**Sidenote:
Remember to always build your code with all warnings enabled. The compiler will give you very useful diagnostics that will help you quickly find solutions to problems like this. For GCC, as a minimum, use gcc -Wall myprogram.c
Two obvious problems:-
Line 46 : simpson(Integral i);
...should be just simpson(i);. Putting a type there is simply an error.
And this, later:
double simpson(Integral i)
.. tells the compiler to pass in Integral object yet you use the indirection operator i.e i->limits as though you'd been passed a pointer. The easiest fix is to make the function expect a pointer, like this:
double simpson(Integral *i)