Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

c - Why does omitting explicit 'int' type for a parameter fail to compile in gcc sometimes?

When declaring variables in C you can omit the type sometimes if you want to declare an int.

Why does omitting explicit 'int' type for a parameter fail to compile in gcc with other non-int parameters, unless declared in the K&R style?

This code generates an error:

main(argc, char *argv[])
{
  /* . . . */
}

With the following output:

$gcc XXX.c -oXXX
XXX.c:X:X: error: expected ‘)’ before ‘char’
 main(argc, char *argv[])
            ^

However, if I write K&R style types for the parameters I can omit specifying an int type for the first parameter:

main(argc, argv)
char *argv[];
{
  /* . . . */
}

And that compiles fine.

I suspect the reason is that when making the first C standard they decided that the K&R automatic-int notation should be completely seperate from the newer syntax for function parameters, especially since by the time the standard was being pulled together the automatic-int notation was likely already considered poor notation.

My interest in these rules is academic, I don't generally write this old-style C.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The compiler is employing one of two grammars.

When applying the K&R grammar, undeclared parameters are allowed, and default to ints.

When applying the non-K&R grammar, all parameters must comply with the parameter declaration syntax i.e. declared with types and names.

You invoke one or the other by choosing the corresponding declaration style.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...