开发者

instantiating functions and variable initialization at same time

开发者 https://www.devze.com 2023-01-27 12:33 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号