C89 (C90, ANSI-C) does not allow intermixing variables declaration with code. I wonder to what extent a variable initialization is considered "code".
Perhaps it's only valid to initialize with constant expressions?
Specifically, if I'm writing C code and I want to play safe (maximize compatibility with ANSI-C compilers), should the following be considered safe?
void f1(void) {
int x = 30;
int y = 40;
int z;
/* ... */
}
void f2(void) {
int x = 30, y = 40;
int z;
/* ... */
}
#define MYCONST (90)
void f3(void) {
int x = 3;
int y = 4 + MYCONST;
int z;
/* ... */
}
void f4(void) {
int x = 3;
int y = time(NULL);
int z = 10 + x;
/* ... */
}
Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.
int a, b; a = b = 10; int a, b = 10, c = 20; Method 5 (Dynamic Initialization : Value is being assigned to variable at run time.)
To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.
Initializing a variable as Telastyn pointed out can prevent bugs. If the variable is a reference type, initializing it can prevent null reference errors down the line. A variable of any type that has a non null default will take up some memory to store the default value.
should the following be considered safe?
All of your posted code is safe.
However, it is not legal to declare a variable after code that is not variable declaration.
void foo()
{
int i = 0;
i = 2; // Does not declare a variable.
int j = 10; // Not legal.
}
The above code works with gcc. However, if you use the -pedantic
flag, you will see a warning message that will look something like:
soc.c:5:4: warning: ISO C90 forbids mixed declarations and code [-Wpedantic]
int j = 10;
C89 does not allows mixing declarations and statements in the same scope. We are referring here to declarations and statements inside functions as statements are not allowed outside functions in C.
int a = foo(a, b); /* declared at block-scope */
The line above is a (valid C89) declaration, not a statement so all your functions f1, f2, f3, and f4 are valid C89.
However you are allowed to mix declarations and statements in different scopes:
void bar(void)
{
int i = 0; /* declaration */
i++; /* statement */
{
int j = 0; /* declaration */
j++; /* statement */
}
}
The function above is valid C89.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With