Skip to content

Error: Initializer element is not constant: Quick Fix

  • by
  • 3 min read

Programming has become a lot easier these days thanks to the numerous resources available on the internet. That said, there are still hoops that every developer needs to jump through in order to get their code to run. Random bugs and glitches are still very much an everyday thing for most if not all programmers. 

In this article, we’re talking about the “error: initializer element is not constant” issue, its causes and what you can do to fix the problem.


What causes this error?

There are actually a number of reasons why you’d see this error. However, the main reason why this happens is that you’ve declared the element outside of the main or any other functions using it, implicitly stating that the variable has a static storage location. This means that the initialised variable is now global. In C, there’s a rule stating that global variables need to be initialised with constant expressions, which is the point of error here. 

Also read: What is regsvr32 kernelbase.dll? Quick Fix for crashes


How to fix this?

The fix is relatively simple. You can either:

  • Declare a global variable with a constant value (or expression)
  • Declare and use a local variable for the main or a specific function. 

Depending on your code and what you’re trying to do, you might want to shy away from global variables here. Unless you’re comparing two or more values or have an explicit need for a global variable, it’s best to declare and use local variables for any specific methods that you might have written and will use when the program executes. 

What is Metadata? Types and benefits | Candid.Technology
Photo by Shahadat Shemul

Alternatively, you might want to simply declare a global variable with a constant value or expression. For example:

// Here's how you declare global varaibles
#include <stdio.h>

int x = 1; // global variable
int main() {

int y = 2; // local variable
return 0;
}

The snippet mentioned above declares a global variable, x, which has a constant value of five. Hence you can use this variable anywhere in your code without triggering any errors. If you’re using an expression to declare the variable, make sure that the expression is valid and has all the inputs it needs. 

Also read: No bootable devices found: Quick Fix

Yadullah Abidi

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: yadullahabidi@pm.me.

>