C - Invalid syntax allowed by compiler? - c

When I learned C using Microsoft Visual Studio, it didn't allow me to create an array with a non-constant size. I had to either put a value like int arr[5]; or do #define size 5 and do int arr[size];. However today using Clion, I noticed it allows me to do the following:
#include <stdio.h>
int main()
{
printf("Enter a value: ");
int x;
scanf("%d", &x);
int arr2[x];
for (int i = 0; i < x; i++)
{
arr2[i] = i;
printf("Array at %d is %d.\n", i, arr2[i]);
}
return 0;
}
This C code compiles and runs without any problems -- no segment fault or anything. What's going on? Is this legal C code and I just learned in an IDE that didn't allow it, or is this invalid C code and I'm just using a bad compiler? On my other computer which is using Linux, I even installed GCC 7.2 and the same syntax is allowed. I don't understand. Is this a CLion issue, CMake issue, or a C lang issue?
My compiler and CMake are listed below. Thanks.

This is valid C. It is referred to as a variable length array (VLA). This feature was added to the language as part of the C99 standard.
MSVC is well known for not supporting many C99 and later features, including VLAs.

Related

expression did not evaluate to a constant ERROR code

So I am trying to learn C and I am trying to make this code so it will sort of the array's elements from lowest to highest, it's obviously not complete but I just wanted to see the random numbers printed.
Anyway, I am getting an error E0028 & C2131 (Visual Studios) that says "expression must have a constant value" & "expression did not evaluate to a constant." The int goals[howMany];is where VS is telling me I have an error
int main()
{
int i, temp, swapped;
int howMany = 10;
int goals[howMany];
for (i = 0; i < howMany; i++) {
goals[i] = (rand() % 25) + 1;
}
printf("Original List\n");
for (i = 0; i < howMany; i++) {
printf("%d \n", goals[i]);
}
return 0;
}
This is exactly how the code is written out in the tutorial I am watching and they are using Code:Blocks. I know sometimes those two compilers can be different but I was hoping someone can let me know what's going on or how to fix this.
Visual studio doesn't support variable length arrays. C is a little tricky, and the compiler/flags you use matters. For example, if you were to compile with the gcc compiler, using the -std=c99 flag would allow you to run your code with no errors (since -std=c99 supports variable length arrays).
I'm not sure exactly how compilation in Visual Studio works, but that's your problem. I usually don't like C programming in VS for this reason. It's much easier for me to use something like Vim, and compile at the command like so that I can specify compiler settings.
In order to use rand(), you need to include the according lib and then "plant a rand seed" : take a look at C Rand Function
const howMany = 10;
This most likely is just the compiler you are using. I suppose it's a safe guard to prevent a segmentation fault. If howMany variable is changed after being used to initialize the array then a seg fault will will definitely result.A seg fault is when you access something out of bounds. If you try to change a const variable then the compiler will not let you.By making howMany const this will prevent any such errors.

is there a different syntax for functions with double in c?

I'm new to coding in C so im sure this is a basic question. in my mind, this code should read an input, run the rcall() which does nothing, and output the same value. This works perfectly with int() values, but as soon as I switch to double, the output doesn't change from -6158. How do fix this logic error?
double input, output, rcall(x);
int main(void){
scanf("%lf", &input); /*read the input*/
output=rcall( input); /*call the function*/
printf("%lf", output); /*print the output*/
}
double rcall(x){ /*this function does nothing*/
return x;
}
The problem here is that you are using a 17 year old compiler, or have your current compiler incorrectly configured to compile the code as if it was older than 17 years.
The declaration double rcall(x); is nonsense in modern C.
But ancient C allowed sloppy declarations where not all types were specified, or even allowed you to call functions that had no declaration. The compiler would then always "helpfully" assume that those types that weren't explicitly specified are all int. If it turned out that they actually weren't, your program would then crash and burn.
This sheer stupid system was removed from the C language in the year 1999, with the "C99" standard. In modern C, your declaration should be
double rcall (double x);
and the definition should be
double rcall (double x)
{
return x;
}
In case you are using GCC, you can configure it to correct code according to modern standard C by adding the options gcc -std=c11 -pedantic-errors. Then you would have gotten a compiler error for the original code.
Declare x as a double type
double rcall(double x)

Matrix not zero-filled on declaration

I was trying to debug my code in another function when I stumbled upon this "weird" behaviour.
#include <stdio.h>
#define MAX 20
int main(void) {
int matrix[MAX][MAX] = {{0}};
return 0;
}
If I set a breakpoint on the return 0; line and I look at the local variables with Code::Blocks the matrix is not entirely filled with zeros.
The first row is, but the rest of the array contains just random junk.
I know I can do a double for loop to initialize manually everything to zero, but wasn't the C standard supposed to fill this matrix to zero with the {{0}} initializer?
Maybe because it's been a long day and I'm tired, but I could've sworn I knew this.
I've tried to compile with the different standards (with the Code::Blocks bundled gcc compiler): -std=c89, -std=c99, std=c11 but it's the same.
Any ideas of what's wrong? Could you explain it to me?
EDIT:
I'm specifically asking about the {{0}} initializer.
I've always thought it would fill all columns and all rows to zero.
EDIT 2:
I'm bothered specifically with Code::Blocks and its bundled GCC. Other comments say the code works on different platforms. But why wouldn't it work for me? :/
Thanks.
I've figured it out.
Even without any optimization flag on the compiler, the debugger information was just wrong..
So I printed out the values with two for loops and it was initialized correctly, even if the debugger said otherwise (weird).
Thanks however for the comments
Your code should initialize it to zero. In fact, you can just do int matrix[MAX][MAX] = {};, and it will be initialized to 0. However, int matrix[MAX][MAX] = {{1}}; will only set matrix[0][0] to 1, and everything else to 0.
I suspect what you are observing with Code::Blocks is that the debugger (gdb?) is not quite showing you exactly where it is breaking in the code - either that or some other side-effect from the optimizer. To test that theory, add the following loop immediately after the initialization:
``` int i,j;
for (i = 0; i < MAX; i++)
for (j = 0; j < MAX; j++)
printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
```
and see if what it prints is consistent with the output of the debugger.
I am going to guess that what might be happening is that since you are not using matrix the optimizer might have decided to not initialize it. To verify, disassemble your main (disass main in gdb and see if the matrix is actually being initialized.

On understanding how printf("%d\n", ( { int n; scanf("%d", &n); n*n; } )); works in C

I came across this program via a quora answer
#include<stdio.h>
int main() {
printf("%d\n", ( { int n; scanf("%d", &n); n*n; } ));
return 0;
}
I was wondering how does this work and if this conforms the standard?
This code is using a "GNU C" feature called statement-expressions, whereby a parentheses-enclosed compound statement can be used as an expression, whose type and value match the result of the last statement in the compound statement. This is not syntactically valid C, but a GCC feature (also adopted by some other compilers) that was added presumably because it was deemed important for writing macros which do not evaluate their arguments more than once.
You should be aware of what it is and what it does in case you encounter it in code you have to read, but I would avoid using it yourself. It's confusing, unnecessary, and non-standard. The same thing can almost always be achieved portably with static inline functions.
I don't believe it does work... n has local scope within the braces... when you exit the braces, n becomes undefined though I suppose is could still exist somewhere on the stack and might work. It's begging for implementation issues and I guarantee is implementation dependent.
One thing I can tell you is that anyone working for me who wrote that would be read the riot act.
It works. I get no warnings from gcc, so I suppose that it conforms to the standard.
The magic is the closure:
{ int n; scanf("%d", &n); n*n; }
This nugget scans an integer from the console (with no error checking) and squares it, returning the squared number. In ancient implementations of C, the last number on the stack is returned. The n*n puts the number on the stack.
That value gets passed to the printf:
printf("%d\n", <scanned>);
So, to answer your questions: Yes, it works. Yes, it's "standard" (to the extent that anyone follows the standard entirely). No, it's not a great practice. This is a good example of what I by knee-jerk reaction call a "compiler love letter", designed mostly to show how smart the programmer is, not necessarily to solve a problem or be efficient.

Using c macro for variables

I want to access several variables of the form:
int arr1=1;
int arr2=1;
int arr3=1;
So I wrote
#define arr(i) arr##i
but following code piece doesnt work as i expect
#include <stdio.h>
int main(){
int arr1=1;
int arr2=1;
int arr3=1;
int j;
for(j=1; j<3; j++)
printf("%d",arr(j));
return 0;
}
You cannot do this. Variable names don't exist at runtime in C.
Your macro will expand to arrj, which is an undefined variable name. Use a proper array:
int arr[] = { 1, 1, 1 };
then print arr[j], but loop like this:
for(j = 0; j < sizeof arr / sizeof *arr; ++j)
printf("%d\n, arr[j]);
The macro code is used for pre-processor phase and not for the runtime phase
if you generate your preprocessor code with gcc -E. You will see that your code is equivalent to:
int main(){
int arr1=1;
int arr2=1;
int arr3=1;
int j;
for(j=1; j<3; j++)
printf("%d",arrj);
return 0;
}
When you build your program, the gcc generate anoter c code from your c code and in which it replace all macros in your code by the macro contents( This phase is called preprocesser phase). and then generate asm code and then generate the binary file.
You can see the generated c code (from your code) by the gcc -E: code of preprocessor phase
So that's going to produce arrj as a result.
The macro phase of C is something that happens before the program is run, even before it is parsed as actual C.
Long ago, the preprocessor was a totally separate program that knew very little about the C language.
Like most compilers today, cc back then just ran the different phases. Before it ran the compiler, assembler, and linker, it ran cpp, the C preprocessor.
And cpp just parsed the definitions, then it expanded the macros, and then it quit. Then cc would run the compiler. These days, the macro expansion is built in to the compiler proper but it processes the textual input of the program according to the original design.
There is still a /usr/bin/cpp on some systems today, but it's usually just a shell script that runs the compiler image with options that say don't compile.

Resources