instantiating functions and variable initialization at same time
Why doesn't the code below get compiled ? For sake of brevity, I woul开发者_Python百科d like the code to be written in this manner, which seems syntactically OK, but Linux gcc compiler complains
#include <stdio.h>
void fn(int in, char ch, char* str);
int main()
{
fn(int i2 = 20, char ch2 = 'Z', char* str2 = "Hello");
printf("in2 = %d, ch2 = %c, str2 = %s\n", in2, ch2, str2);
return;
}
void fn(int in, char ch, char* str)
{
printf("int = %d\n", in);
printf("ch = %c\n", ch);
printf("str = %s\n", str);
return;
}
Because in c89 (ANSI C) you can declare variables only at the beginning of a block.
int main()
{
int i2 = 20; char ch2 = 'Z'; char* str2 = "Hello";
fn(i2, ch2,str2);
printf("in2 = %d, ch2 = %c, str2 = %s\n", in2, ch2, str2);
return;
}
EDIT
In c99, even thought you can in other parts, you can't decalre variables inside of expressions (like a function call).
You should declare your variables outside the function call and everything will be OK.
精彩评论