The following is a visual basic code

dim Msg1(5)

Msg1(1) = "xMessage1"
Msg1(2) = "xxMessage2"
Msg1(3) = "xxxMessage3"
Msg1(4) = "xxxxMessage4"
Msg1(5) = "xxxxxMessage5"

For cnt = 1 To 5
    Debug.Print Msg1(cnt)
Next cnt

How can I do the same thing with ANSI C? (Instead of Debug.Print can be printf)

Recommended Answers

All 5 Replies

One way:

#include <stdio.h>

int main(void)
{
   const char *Msg1[] =
   {
      "xMessage1",
      "xxMessage2",
      "xxxMessage3",
      "xxxxMessage4",
      "xxxxxMessage5",
   };
   size_t i;
   for ( i = 0; i < sizeof Msg1 / sizeof *Msg1; ++i )
   {
      printf("%s\n", Msg1[i]);
   }
   return 0;
}

This might be closer to a direct translation:

#include <stdio.h>

int main(void)
{
   const char *Msg1[5] =
   {
      "xMessage1",
      "xxMessage2",
      "xxxMessage3",
      "xxxxMessage4",
      "xxxxxMessage5",
   };
   size_t cnt;
   for ( cnt = 0; cnt < 5; ++cnt )
   {
      printf("%s\n", Msg1[cnt]);
   }
   return 0;
}
commented: looks good +18

I tried your code and it is works, but there is a point that I dont understand. In the line

for ( i = 0; i < sizeof Msg1 / sizeof *Msg1; ++i )

why is referred two times the 'sizeof Msg1' (sizeof Msg1 / sizeof *Msg1) separated by '/' ?

>why is referred two times the 'sizeof Msg1' (sizeof Msg1 / sizeof *Msg1) separated by '/' ?
The size of the array in bytes (sizeof Msg1) divided by the size of a single element in bytes (sizeof *Msg1) gives you the number of elements in the array. It's a way of avoiding magic numbers by calculating the number of elements at compile-time.

I see, thanx a lot for your response.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.