1

a variable/function can be declared any number of times but it can be defined only once. What does that actually mean??

I tried to understand that statement on online compilers and I was expecting to show error but it didnt.

#include <stdio.h>
int x=10;

int main() {
    x=20;
    x=30;

    printf("%d",x);
}

expected output: i expected to show error because i have defined variable x and assigned three different values 10,20,30. the concept says you can declare variable any number of times but can define only once since two different locations cant be given to the same variable actual output: 30

Federico klez Culloca
  • 22,898
  • 15
  • 55
  • 90

2 Answers2

9

x = 10; isn’t a definition. It’s an assignment. You can assign as many times as you like.

int x; is a definition (and, at the same time, also a declaration). Likewise, extern int x; is a declaration (without a definition). To illustrate the concept you were asking about, the following is valid C:

// Duplicate declaration: OK
extern int x;
extern int x;

// Definition: OK
int x;
// int x; // Duplicate definition: ERROR

// Definition with initialisation: OK
int y = 42;

// (Re)assignment: OK inside function.
x = 1;
y = 2;

For functions, the syntax is different. To declare a function, write its prototype. To define it, add a function body:

// Declaration:
int f(void);
// Also possible, but unnecessary:
extern int f(void);

// Definition:
int f(void) { return 42; }
Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
  • 1
    Nice answer. I got a few things wrong, and when I saw your answer I did not see the point in correcting my answer. Upvoted. – klutt Jun 05 '19 at 15:39
  • 1
    @Broman: That's a shame: Stack Overflow works best when there are multiple answers. – Bathsheba Jun 05 '19 at 15:46
  • @Bathsheba This answer covered everything I wanted to say. There's no point in adding an answer if your answer does not provide anything new. – klutt Jun 05 '19 at 15:50
  • *x = 10; isn’t a definition. It’s an assignment.* The `x = 10` portion is an *initialization*, and that's different from an assignment. – Andrew Henle Jun 05 '19 at 15:55
  • @AndrewHenle I was talking about the standalone statement, not the fragment `x = 10` as part of the statement `int x = 10;`. – Konrad Rudolph Jun 05 '19 at 16:53
-1

I just wanted to add that you would get an error if you had defined the variable as a constant, i.e.

const int x = 10;

x = 15; // This will throw a compile-time error

As constants may only be assigned once during definition, hence the name constant.

https://www.programiz.com/c-programming/c-variables-constants

Daniel Kappelle
  • 181
  • 1
  • 6