-
About the complier
Rcently,i come across a problem,i wrote a code as following:
Code:
#include <stdio.h>
//#include <stdlib.h>
void ex(int &a,int &b)
{
int t;
t = a;
a = b;
b = t;
}
int main()
{
int a,b;
a = 1;
b = 2;
printf("%d%d\n",a,b);
ex(a,b);
printf("%d%d\n",a,b);
//printf("Hello world!\n");
return 0;
}
but when i copy it into codeblocks and wDEV c++,then i rebuild it ,it could not success,but when i rebuild it in c-free,it works!~~nothing wrong.
could someone tell me why?
Thank you !
-
What error messages did you get?
In programming it's all about error messages. They tell you, well, what errors you make. (Which is a good thing, btw)
-
Right. Are you assigning an address to an integer on purpose?
Code:
void ex(int &a,int &b)
{
int t;
t = a; // Because you're doing that here.
a = b;
b = t;
}
-
Wrong, msh. The code is actually C++ (the arguments of ex() are references, sometimes known as aliases, not pointers). The assignments are not of pointers.
The problem is probably related to errors in installation of the compilers or development environments, or settings in the particular project. As CommonTater said, the error messages will be key to identifying the problem.
If the code is being compiled as C, it will not compile unless the compiler goes well beyond the C standard - C does not support reference arguments.
-
-
the cobeblocks tell me:
||=== Exchg3, Debug ===|
/media/installation/CodeBlocks/Examples/Exchg3/main.c|4|error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token|
/media/installation/CodeBlocks/Examples/Exchg3/main.c||In function ‘main’:|
/media/installation/CodeBlocks/Examples/Exchg3/main.c|17|warning: implicit declaration of function ‘ex’|
||=== Build finished: 1 errors, 1 warnings ===|
-
Clearly you didn't bother to read - or at least put effort into understanding - previous posts.
The first error message is a consequence of compiling C++ code as C. The & in the first two arguments of ex() are not valid in C, and the compiler expects to find something else - as the error message says.
The second warning message is a side effect of the first error. Because of the first error, the compiler has no visibility of a function named ex() and, in C, an attempt to call an undeclared function implicitly declares it (the warning occurs because such implicit declaration of a function is deprecated - scheduled for removal from a future version of the C standard).
The simplest fix is probably to rename main.c as main.cc (as .cc files are compiled as C++ by default). Alternatively, change project settings for main.c so it is compiled using g++ (the C++ compiler driver) rather than gcc (which will compile a .c file as C, not C++).