syntax error in C prog - c

I am trying to compile my code with a "C" compiler in my IDE. But don't know what the problem is with these few lines.
the error : syntax error near '='
the errors : '_print': different length of parameter lists and '_print':too many actual parameters
BUT the same code runs perfectly with "C++" compiler. I just get error on "C" compiler.
Can anyone give me any idea about it ?

C does not have function overload, nor default arguments as C++ does, so if you need to handle int and long differently, you will need one function per type, like this:
void print_int(int n, int base);
void print_long(long n, int base);
But in your code, since you are just calling the long version in the int function, you can just have one function:
void print(long n, int base);
and if it is called on int, the argument is automatically promoted to long.
int n = 123;
print(n, 10);

Related

Confused about detecting the errors of this code in c programming language?

The code given below is an exercise that our teacher gave to prepare us for exams.
We are supposed to find the errors that occur in this code and fully explain them .
#define SIZE 10
int start (void a,int k) {
const int size=10;
char array[size];
char string[SIZE];
mycheck(3,4);
array[0]=string[0]='A';
printf("%c %c\n", array[0], string[0]);
myRec(7);
}
int mycheck(int a , int b) {
if (a==0 || b==0 ) {
return 0;
}
else {
return (a*b);
}
}
int myRec(int x) {
if(x==0)
return 0;
else
printf("%d,",x);
myRec(x--);
}
I have found these errors so far:
1.int start (void a,int k)
explanation: We can't have a variable of type void, because void is an incomplete type
2.const int size=10;
explanation:we can't use variable to define size of array
(problem is when I run it in dev-c++ it doesn't show an error so I'm not sure about this)
3.mycheck(3,4);
explanation: prototype of function mycheck() is not declared, so the function mycheck is not visible to the compiler while going through start() function
4.A friend told me that there is an error in function myRec because of this statement myRec(x--);
(I don't really get why is this an error and how you can I explain it?)
5.Main() function doesn't exist.
I'm not sure about this but if i run the code (in dev-c++) without main function I get a compilation error
I'm not sure if the errors that I pointed out are 100% right or if I missed an error or if I explained them correctly.
Please correct me if any of the above is wrong!
a friend told me that there is an error in function myRec cuz of this
statement myRec(x--);
It will lead to stackoverflow. Due to post-decrement, the actual argument passed to function myRec(), never decreases and therefore the condition:
if(x==0)
return 0;
will never become true. Regarding your rest of the errors, it depends on the compiler version being used:
For example C99, you are allowed to have variable size arrays like this:
const int size=10;
char array[size];
char string[SIZE];
but pre C99, you would have to use malloc or calloc. For your functions used without prototype, most compilers would generate a warning and not error and also due to no #include<stdio.h> statement, your printf would also lead to a warning.i Again, lot of these things are compiler dependent.
1.int start (void a,int k)
explanation: We can't have a variable of type void ,because void is an
incomplete type
Correct.
2.const int size=10;
explanation:we can't use variable to define size of array (problem is
when i run it in dev-c++ it doesnt show an error?so im not sure about
this!)
This is also correct, that char array[size];, where size is not a compile-time constant, is invalid in C89. However, in C99 and newer, this is actually valid and would create a variable-length array. It is possible that your Dev-C++ IDE is using GCC with the language set to C99 or newer, or has GNU C extensions enabled to enable this feature.
3.mycheck(3,4);
explanation: prototype of function mycheck() is not declared.So the
function mycheck is not visible to the compiler while going through
start() function
Correct. This can be fixed either by declaring the function's prototype before the start() function, or just moving the whole function to the top of the file. As noted by Toby Speight in the comments, in C89, this should not actually be a compiler error, since functions are implicitly declared when they are used before any actual declaration as int (), i.e. a function returning int with any arguments, which is compatible with the declarations of mycheck and myRec. It is however bad practice to rely on this, and implicit function declaration does not work in C99 or newer.
4.a friend told me that there is an error in function myRec cuz of this statement myRec(x--);
(I don't really get why is this an error and how you can explain it?)
This function is a recursive function. This means it calls itself within itself in order to achieve a kind of looping. However, this function as it is currently written would run forever and cause an infinite loop, and since it is a recursive function, and needs a new stack frame each time it is called, it will most likely end in a stack overflow.
The function is written with this statement:
if(x==0)
return 0;
This is intended to terminate the recursion as soon as x reaches 0. However, this never happens, because of this line of code here:
myRec(x--);
In C, postfix -- and ++ operators evaluate to their original value before the addition or subtraction:
int x = 5;
int y = x--;
/* x is now 4; y is now 5 */
However, using the prefix version of these operators will evaluate to their new value after adding / subtracting 1:
int x = 5;
int y = --x;
/* x is now 4; y is now 4 */
This means that on each recursion, the value of x never actually changes and so never reaches 0.
So this line of code should actually read:
myRec(--x);
Or even just this:
myRec(x - 1);
5.Main() function doesn't exist ...again im not sure about this but if i run the code (in dev-c++) without main function i get a compilation
error
This one could either be right or wrong. If the program is meant to run on its own, then yes, there should be a main function. It's possible that the function start here should actually be int main(void) or int main(int argc, char *argv[]). It is entirely valid however to compile a C file without a main, for example when making a library or one individual compilation unit in a bigger program where main is defined in another file.
Another problem with the program is that myRec is used before it is declared, just like your point 3 where mycheck is used before it is declared.
One more problem is that the functions start and mycheck are declared to return int, yet they both do not contain a return statement which returns an int value.
Other than that, assuming that this is the entire verbatim source of the program, the header stdio.h isn't included, yet the function printf is being used. Finally, there's the issue of inconsistent indentation. This may or may not be something you are being tested for, but it is good practice to indent function bodies, and indentation should be the same number of spaces / tab characters wherever it's used, e.g.:
int myRec(int x) {
if(x==0)
return 0;
else
printf("%d,",x);
myRec(x--);
}
1) Hello friend your Recursive function myRec() will go infinite because it
call itself with post detriment value as per C99 standard it will
first call it self then decrements but when it call itself again it have
to do the same task to calling self so it will never decrements and new
stack is created and none of any stack will clear that recursion so
stack will full and you will get segmentation fault because it will go
beyond stack size.
2) printf("%d,",x); it should be printf("%d",x); and you should include #include library.
I think your another mistake is you are calling your mycheck() and you
returning multiplication of two integer but you are not catch with any
value so that process got west.So while you are returning something you
must have to catch it otherwise no need to return it.
3) In this you Program main() function missing. Program execution starts
with main() so without it your code is nothing. if you want to execute
your code by your own function then you have to do some process but
here main() should be present.or instead of start() main() should
be present.
4) you can also allocate any char buffer like this int j; char array[j=20];
your code should be like this.
#include<stdio.h>
#define SIZE 10
int mycheck(int a , int b) {
if (a==0 || b==0 ) {
return 0;
}
else {
return (a*b);
}
}
int myRec(int x) {
if(x==0)
return 0;
else
printf("%d",x);
myRec(--x);
}
void main (int argc, char** argv) {
const int size=10;
char array[size];
char string[SIZE];
int catch = mycheck(3,4);
printf("return value:: %d\n",catch);
array[0]=string[0]='A';
printf("%c %c\n", array[0], string[0]);
myRec(7);
printf("\n");
}
Enjoy.............

expected expression before double

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

Passing a structure (pointer to structure?) to a function

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", &degree_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)

Troubling converting string to long long in C

I'm having trouble getting the atoll function to properly set a long long value in c. Here is my example:
#include <stdio.h>
int main(void) {
char s[30] = { "115" };
long long t = atoll(s);
printf("Value is: %lld\n", t);
return 0;
}
This prints:
Value is: 0
This works though:
printf("Value is: %lld\n", atoll(s));
What is going on here?
First, let's answer your question:
#include <stdio.h>
#include <stdlib.h> // THIS IS WHAT YOU ARE MISSING
int main(void) {
char s[30] = { "115" };
long long t = atoll(s);
printf("Value is: %lld\n", t);
return 0;
}
Then, let's discuss and answer 'why?':
For compatibility with very old C programs (pre-C89), using a function without having declared it first only generates a warning from GCC, not an error (As pointed out by the first comment here, also implicit function declarations are allowed in C89, therefore generating an error would not be appropriate, that is another reason to why only a warning is generated). But the return type of such a function is assumed to be int (not the type specified in stdlib.h for atoll for instance), which is why the program executes unexpectedly but does not generate an error. If you compile with -Wall you will see that:
Warning: Implicit declaration of function atoll
This fact mostly shocks people when they use atof without including stdlib.h, in which case the expected double value is not returned.
NOTE: (As an answer to one of the comments of the question) This is the reason why the results of atoll might be truncated if the correct header is not included.

Variable has value in one function, and is 0 when passed to another?

So my problem is, I am passing a variable by value (it is a float) from one function in my C code to another function. For some reason the variable is 0 after the pass. I have multiple other floats being passed by value, that are not 0 (all in the same function call), so I can't understand why this one is. It might be as simple as some typo that I am just not seeing:
int cuda_call(float *h_DataA, float *h_Kernel, int numSmooths, float kernelSum, int KERNEL_R, int KERNEL_W, int DATA_W){
printf("\n What am I here?: %f \n", kernelSum);
convolutionProgram(h_DataA, h_Kernel, numSmooths, kernelSum, KERNEL_R, KERNEL_W, DATA_W);
return 1;
}
extern "C" void convolutionProgram(float *h_DataA, float *h_Kernel, int numSmooths, float kernelSum, int KERNEL_R, int KERNEL_W, int DATA_W);
void convolutionProgram(float *h_DataA, float *h_Kernel, int numSmooths, float kernelSum, int KERNEL_R, int KERNEL_W, int DATA_W){
printf("\n what am I now? %f \n", kernelSum);
float
*d_DataA,
*d_DataB,
*d_Temp,
*d_Kernel;
.......
}
By the time I get to that second print in the called function, it is 0.
Maybe you have somehow ended up mixing calling conventions (ABIs). For instance, the first compilation unit may be performing a cdecl call, while the second one is compiled with fastcall.
http://en.wikipedia.org/wiki/X86_calling_conventions
Is it possible that you have not rebuilt the object file for one of the c files? This looks like a signature mismatch which can arrise from a function signature change without rebuilding both object files.

Resources